Chapter 4: Multithreaded Programming

Similar documents
Chapter 4: Multithreaded Programming

Chapter 4: Multithreaded Programming

OPERATING SYSTEM. Chapter 4: Threads

Chapter 4: Threads. Chapter 4: Threads

Chapter 4: Threads. Chapter 4: Threads

Chapter 4: Threads. Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads

Chapter 4: Threads. Operating System Concepts 9 th Edition

Chapter 4: Threads. Chapter 4: Threads. Overview Multicore Programming Multithreading Models Thread Libraries Implicit Threading Threading Issues

Che-Wei Chang Department of Computer Science and Information Engineering, Chang Gung University

Chapter 4: Multithreaded Programming

CS307: Operating Systems

Chapter 4: Threads. Operating System Concepts 9 th Edition

Chapter 4: Multithreaded Programming Dr. Varin Chouvatut. Operating System Concepts 8 th Edition,

I.-C. Lin, Assistant Professor. Textbook: Operating System Concepts 8ed CHAPTER 4: MULTITHREADED PROGRAMMING

EI 338: Computer Systems Engineering (Operating Systems & Computer Architecture)

Chapter 4: Multithreaded Programming. Operating System Concepts 8 th Edition,

Outline. Threads. Single and Multithreaded Processes. Benefits of Threads. Eike Ritter 1. Modified: October 16, 2012

CSE Opera,ng System Principles

Operating Systems 2 nd semester 2016/2017. Chapter 4: Threads

Chapter 4: Threads. Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux Threads Java Threads. Operating System Concepts

Chapter 4: Multi-Threaded Programming

Chapter 4: Multithreaded

Chapter 5: Threads. Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux Threads Java Threads

Threads. What is a thread? Motivation. Single and Multithreaded Processes. Benefits

Agenda Process Concept Process Scheduling Operations on Processes Interprocess Communication 3.2

CSE 4/521 Introduction to Operating Systems

Chapter 4: Threads. Operating System Concepts 9 th Edit9on

CS 450 Operating System Week 4 Lecture Notes

CSCE 313 Introduction to Computer Systems. Instructor: Dezhen Song

CSCE 313: Intro to Computer Systems

Multithreaded Programming

Chapter 4: Threads. Operating System Concepts. Silberschatz, Galvin and Gagne

Chapter 5: Processes & Process Concept. Objectives. Process Concept Process Scheduling Operations on Processes. Communication in Client-Server Systems

Chapter 5: Threads. Outline

Chapter 4: Threads. Operating System Concepts 8 th Edition,

Chapter 4 Multithreaded Programming

Chapter 3: Processes. Operating System Concepts 8th Edition

Motivation. Threads. Multithreaded Server Architecture. Thread of execution. Chapter 4

Threads Implementation. Jin-Soo Kim Computer Systems Laboratory Sungkyunkwan University

Semantics of fork() and exec()

CS420: Operating Systems

CISC2200 Threads Spring 2015

Chapter 4: Threads. Operating System Concepts with Java 8 th Edition

Processes and Threads

Lecture 4 Threads. (chapter 4)

COP 4610: Introduction to Operating Systems (Spring 2015) Chapter 4: Threads. Zhi Wang Florida State University

Processes and Threads

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Process Description and Control

4.8 Summary. Practice Exercises

Operating Systems Prof. Ashok K Agrawala

TDIU25: Operating Systems II. Processes, Threads and Scheduling

Chapter 5: Threads. Single and Multithreaded Processes

Lecture 2 Process Management

Thread Concept. Thread. No. 3. Multiple single-threaded Process. One single-threaded Process. Process vs. Thread. One multi-threaded Process

Page 1. Analogy: Problems: Operating Systems Lecture 7. Operating Systems Lecture 7

Exercise (could be a quiz) Solution. Concurrent Programming. Roadmap. Tevfik Koşar. CSE 421/521 - Operating Systems Fall Lecture - IV Threads

Threads. CS-3013 Operating Systems Hugh C. Lauer. CS-3013, C-Term 2012 Threads 1

Thread. Operating Systems (Fall/Winter 2018) Yajin Zhou ( Zhejiang University

CS370 Operating Systems

ICS Principles of Operating Systems

Threads. CS3026 Operating Systems Lecture 06

CSMC 412. Operating Systems Prof. Ashok K Agrawala Ashok Agrawala Set 4. September 2006 CMSC 412 Set 4

Threads. Thread Concept Multithreading Models User & Kernel Threads Pthreads Threads in Solaris, Linux, Windows. 2/13/11 CSE325 - Threads 1

Threads Implementation. Jo, Heeseung

Agenda. Threads. Single and Multi-threaded Processes. What is Thread. CSCI 444/544 Operating Systems Fall 2008

Chapter 4: Threads. Operating System Concepts 9 th Edition

Definition Multithreading Models Threading Issues Pthreads (Unix)

Yi Shi Fall 2017 Xi an Jiaotong University

Multithreading. Reading: Silberschatz chapter 5 Additional Reading: Stallings chapter 4

Concurrency, Thread. Dongkun Shin, SKKU

Process Concept Process in Memory Process State new running waiting ready terminated Diagram of Process State

CS420: Operating Systems

Part V. Process Management. Sadeghi, Cubaleska RUB Course Operating System Security Memory Management and Protection

CHAPTER 2: PROCESS MANAGEMENT

Questions answered in this lecture: CS 537 Lecture 19 Threads and Cooperation. What s in a process? Organizing a Process

!! How is a thread different from a process? !! Why are threads useful? !! How can POSIX threads be useful?

CS370 Operating Systems

CS Lecture 3! Threads! George Mason University! Spring 2010!

Questions from last time

COP 4610: Introduction to Operating Systems (Fall 2016) Chapter 4: Threads. Zhi Wang Florida State University

SMD149 - Operating Systems

! How is a thread different from a process? ! Why are threads useful? ! How can POSIX threads be useful?

Preview. The Thread Model Motivation of Threads Benefits of Threads Implementation of Thread

THREADS. Jo, Heeseung

4. Concurrency via Threads

Threads. Still Chapter 2 (Based on Silberchatz s text and Nachos Roadmap.) 3/9/2003 B.Ramamurthy 1

Lecture Topics. Announcements. Today: Threads (Stallings, chapter , 4.6) Next: Concurrency (Stallings, chapter , 5.

Disciplina Sistemas de Computação

Lecture 5: Process Description and Control Multithreading Basics in Interprocess communication Introduction to multiprocessors

CS162 Operating Systems and Systems Programming Lecture 3. Concurrency: Processes, Threads, and Address Spaces. Review: History of OS

Computer Systems Laboratory Sungkyunkwan University

Notes. CS 537 Lecture 5 Threads and Cooperation. Questions answered in this lecture: What s in a process?

Threads. Raju Pandey Department of Computer Sciences University of California, Davis Spring 2011

Threads. studykorner.org

Processes & Threads. Recap of the Last Class. Microkernel System Architecture. Layered Structure

Start of Lecture on January 22, 2014

Quiz: Simple Sol Threading Model. Pthread: API and Examples Synchronization API of Pthread IPC. User, kernel and hardware. Pipe, mailbox,.

Process and Its Image An operating system executes a variety of programs: A program that browses the Web A program that serves Web requests

CS 326: Operating Systems. Process Execution. Lecture 5

Transcription:

Chapter 4: Multithreaded Programming Chapter 4: Multithreaded Programming Overview Multicore Programming Multithreading Models Threading Issues Operating System Examples Objectives To introduce the notion of a thread a fundamental unit of CPU utilization that forms the basis of multithreaded computer systems Most modern applications or/and programs are multithreaded Threads run within an application or a process Multiple tass with the application can be implemented by separate threads To examine issues related to multithreaded programming 4.3! Motivation 4.2! Update display Fetch data Spell checing Answer a networ request Process creation is heavy-weight while thread creation is light-weight Can simplify code, increase efficiency Kernels are generally multithreaded 4.4!

Multithreaded Server Architecture Benefits client (1) request server (3) resume listening for additional client requests (2) create new thread to service the request thread A single application may be required to perform several similar tass. For example a busy web server may process thousands of web requests concurrently. Creating one process for each client request is cumbersome (resource-intensive) and time-consuming A single application may need to do multiple tass. For example, a web browser (client) need to display images or text (one thread) while another thread retrieves data from the networ Responsiveness may allow continued execution if part of process is bloced, especially important for user interfaces Resource Sharing threads with a process share resources of the process by default, easier than shared memory or message passing that must be explicitly arranged by the programmer Economy thread creation is much cheaper than process creation, thread switching also has much lower overhead than context switching (switching to a different process) Scalability A process can tae advantage of multiprocessor architectures by running multiple threads of the process simultaneously on different processors (CPUs). 4.5! 4.6! Multicore Programming Concurrency vs. Parallelism Multicore or multiprocessor systems putting pressure on programmers to mae better use of the multiple computing cores. Programming challenges in multicore systems include:! Identifying tass: to divide applications into separate, concurrent tass Balance: tass perform equal wor of equal value Data splitting! Data dependency! Testing and debugging! Concurrent execution on single-core system:! single core T 1 T 2 T 3 T 4 T 1 T 2 T 3 T 4 T 1 time Parallelism on a multi-core system:! Parallelism implies a system can perform more than one tas simultaneously Concurrency supports more than one tas maing progress Single processor / core, scheduler providing concurrency core 1 T 1 T 3 T 1 T 3 T 1 Types of parallelism Data parallelism distributes subsets of the same data across multiple cores, same operation on each! Tas parallelism distributing threads across cores, each thread performing unique operation core 2 T 2 T 4 T 2 T 4 T 2 time 4.7! 4.8!

Amdahl s Law Single and Multithreaded Processes Identifies performance gains from adding additional cores to an application that has both serial and parallel components S is serial portion N processing cores code data registers If application is 75% parallel / 25% serial, moving from 1 to 2 cores results in speedup of 1.6 times As N approaches infinity, speedup approaches 1 / S! files code data files stac registers registers registers stac stac stac thread thread Serial portion of an application has disproportionate effect on performance gained by adding additional cores!! single-threaded process 4.9! 4.10! Thread State multithreaded process Thread State (Cont.) State shared by all threads in process/address space Each Thread has a Thread Control Bloc (TCB) Execution State: CPU registers, program counter, pointer to stac Contents of memory (global variables, heap) Scheduling info: State (more later), priority, CPU time I/O state (file system, networ connections, etc.) Accounting Info: Various Pointers (for implementing scheduling queues) Pointer to enclosing process: PCB State private to each thread Kept in TCB! Thread Control Bloc In Nachos: thread is a class that includes the TCB CPU registers (including, program counter) OS eeps trac of TCBs in protected memory Execution stac what is this? Array, or Lined List, or Execution Stac 4.11! Parameters, temporary variables Keep program counters while called procedures are executing 4.12!

Lifecycle of a Thread Ready Queue And Various I/O Device Queues Thread not running! TCB is in some scheduler queue As a thread executes, it changes state: new: The thread is being created ready: The thread is waiting to run running: Instructions are being executed waiting: Thread waiting for some event to occur terminated: The thread has finished execution Active threads are represented by their TCBs Ready Queue Head Tape Unit 0 Head Dis Unit 0 Head Dis Unit 2 Head Ether Netw 0 Head TCBs organized into queues based on their states 4.13! Embedded systems Elevators, Planes, Medical systems, Wristwatches Single Program, concurrent operations Most modern OS ernels Concurrent requests from networ Again, single program, multiple concurrent operations File server, Web server, and airline reservation systems User threads - management done by user-level threads library without ernel support Three primary thread libraries: POSIX Pthreads! Win32 threads Java thread Kernel threads - supported by the ernel. Virtually all general-purpose operating systems support ernel threads, including: Windows Solaris Linux Mac OS X 4.15! 4.14! Split program into multiple threads for parallelism Tail Lin Registers Other State TCB8 Support for threads may be provided at either the user level, for user threads, or by the ernel, for ernel threads! Parallel Programming (More than one physical CPU) Tail Lin Registers Other State TCB3 Networ Servers Lin Registers Other State TCB2 Tail Lin Registers Other State TCB16 Internally concurrent to deal with concurrent requests by multiple users But no protection needed within ernel Access to shared data by many concurrent users Also bacground utility processing must be done Tail Lin Registers Other State TCB6 User Threads and Kernel Threads Database Servers Lin Registers Other State TCB9 Tail Examples of Multithreaded Programs Separate queue for each device/signal/condition Each queue can have a different scheduler policy Ultimately, a relationship must exist between user threads and ernel threads. 4.16!

Multithreading Models Many-to-One Many-to-One One-to-One Many-to-Many Many user-level threads mapped to single ernel thread One thread blocing causes all to bloc Multiple threads may not run in parallel on a multicore system because only one may be in ernel at a time Few systems currently use this model user thread Examples: Solaris Green Threads! GNU Portable Threads! ernel thread 4.17! 4.18! One-to-One Many-to-Many Model Each user-level thread maps to ernel thread Creating a user-level thread creates a ernel thread More concurrency than many-to-one Number of threads per process sometimes restricted due to overhead Examples Windows NT/XP/2000 Linux Solaris 9 and later Allows many user level threads to be mapped to many ernel threads Allows the operating system to create a sufficient number of ernel threads Solaris prior to version 9 Windows NT/2000 with the ThreadFiber pacage user thread user thread ernel thread ernel thread 4.19! 4.20!

Two-level Model Thread Libraries Similar to M:N, except that it also allows a user thread to be bound to ernel thread Examples IRIX HP-UX Tru64 UNIX Solaris 8 and earlier user thread Thread library provides programmer with API for creating and managing threads Two primary ways of implementing Library entirely in user space with no ernel support. This means that invoing a function in the library results in a local function call in user space, and not a system call Kernel-level library supported directly by the OS Three main thread libraries are in use today: POSIX Pthreads Windows Java ernel thread 4.21! 4.22! Threading Issues Semantics of for() and exec() Semantics of for() and exec() system calls Signal handling Synchronous and asynchronous Thread cancellation of target thread Asynchronous or deferred Does for()duplicate only the calling thread or all threads? Some UNIX have two versions of for If exec() is called immediately after foring, duplicating all threads is unnecessary, as the program specified in the parameters to exec() will replace the entire process Exec() usually wors as normal replace the running process including all threads Thread-local storage 4.23! 4.24!

Signal in UNIX Signal Handling Signals are in UNIX systems to notify a process that a particular event has occurred A signal may be received either synchronously or asynchronously, depending on the source of and the reason for the event being signalled. All signals follow the same pattern: Signal is generated by the occurrence of a particular event Signal is delivered to a process Once delivered, the signal must be handled Examples of synchronous signal include illegal memory access and division of 0. Synchronous signals are delivered to the same process that performed the operation that caused the signal When a signal is generated by an event external to a running process, that process receives the signal asynchronously. Examples include terminating a process with specific eystroes (such as <control><c>) and having a timer expire 4.25! A default signal hander! A user-defined signal handler A signal may be handled by one of the two possible handlers: has occurred Every signal has default handler that ernel runs when handling signal User-defined signal handler can override the default handler For single-threaded, signal delivered to process Where should a signal be delivered a multi-threaded program? Deliver the signal to the thread to which the signal applies Deliver the signal to every thread in the process Deliver the signal to certain threads in the process Assign a specific thread to receive all signals for the process The method for delivering a signal depends on the type of signal Synchronous signals need to be delivered to the thread causing the signal, not other threads Terminating a process signal should be sent to all threads within the process Thread Cancellation Thread-Local Storage Thread cancellation involves terminating a thread before it has completed. Example, 4.26! Multiple threads are concurrently searching through a database, one thread returns the result, the remaining threads might be cancelled Thread-local storage (TLS) allows each thread to have its own copy of data Useful when you do not have control over the thread creation process Different from local variables Thread to be canceled is target thread Cancellation of a target thread may occur in two different scenarios:! Asynchronous cancellation terminates the target thread immediately Deferred cancellation allows the target thread to periodically chec if it should be cancelled This involves in reclaiming the resource allocated to a thread, in which asynchronous cancellation might not be able to free up resource immediately 4.27! Local variables visible only during single function invocation TLS visible across function invocations Similar to static data TLS is unique to each thread 4.28!

Operating System Examples Windows XP Threads Linux Thread Windows Threads Windows implements the Windows API for Win 98, NT, 2000, Win XP, and Window 7 Implements the one-to-one mapping, ernel-level Each thread contains A thread ID uniquely identifying the thread Register set representing the status of the processor Separate user and ernel stacs for when thread runs in user mode or ernel mode Private data storage area used by run-time libraries and dynamic lin libraries (DLLs) The register set, stacs, and private storage area are nown as the context of the thread The primary data structures of a thread include: ETHREAD (executive thread bloc) includes pointer to process to which thread belongs and to KTHREAD, in ernel space KTHREAD (ernel thread bloc) scheduling and synchronization info, ernel-mode stac, pointer to TEB, in ernel space TEB (thread environment bloc) thread ID, user-mode stac, thread-local storage, in user space 4.29! 4.30! Windows XP Threads Data Structures Linux Threads ETHREAD thread start address pointer to parent process Linux refers to processes and threads as tass rather than threads! KTHREAD Thread creation is done through clone() system call scheduling and synchronization information clone() allows a child tas to determine how to share the address space of the parent tas (process) ernel stac Flags control behavior TEB thread identifier flag meaning user stac CLONE_FS File-system information is shared. CLONE_VM The same memory space is shared. thread-local storage CLONE_SIGHAND Signal handlers are shared. CLONE_FILES The set of open files is shared. ernel space user space 4.31! 4.32!