Presentation is loading. Please wait.

Presentation is loading. Please wait.

Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Chapter 4: Threads.

Similar presentations


Presentation on theme: "Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Chapter 4: Threads."— Presentation transcript:

1 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Chapter 4: Threads

2 4.2 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Motivation Most modern applications are multithreaded Threads run within application Multiple tasks with the application can be implemented by separate threads Update display Fetch data Spell checking Answer a network request Process creation is heavy-weight while thread creation is light-weight Can simplify code, increase efficiency Kernels are generally multithreaded

3 4.3 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition A thread is defined as an independent stream of instructions that can be scheduled to run as such by the operating system. To the software developer, the concept of a "function" that runs independently from its main program To go one step further: Imagine a main program that contains a number of functions Then imagine all of these functions being able to be scheduled to run simultaneously and/or independently by the operating system That would describe a "multi-threaded" program.

4 4.4 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition A process is created by the operating system, and requires a fair amount of "overhead" Processes contain information about program resources and program execution state, including: Process ID, process group ID, user ID, and group ID Environment Working directory. Program instructions Registers Stack Heap File descriptors Signal mask and actions

5 4.5 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Threads use and exist within these process resources, yet are able to be scheduled by the operating system and run as independent entities largely because they duplicate only the bare essential resources that enable them to exist as executable code. This independent flow of control is accomplished because a thread maintains its own: Thread ID Stack pointer Stack for local variables, return addresses Registers Scheduling properties (such as policy or priority) Set of pending and blocked signals (signal mask)

6 4.6 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition So, in summary, a thread: Exists within a process and uses the process resources Has its own independent flow of control as long as its parent process exists and the OS supports it May share the process resources with other threads that act equally independently (and dependently) Dies if the parent process dies - or something similar Is "lightweight" because most of the overhead has already been accomplished through the creation of its process

7 4.7 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Because threads within the same process share resources: Changes made by one thread to shared system resources (such as closing a file) will be seen by all other threads Two pointers having the same value point to the same data Reading and writing to the same memory locations is possible, and therefore requires explicit synchronization by the programmer

8 4.8 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Single and Multithreaded Processes

9 4.9 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Benefits Responsiveness – may allow continued execution if part of process is blocked, especially important for user interfaces Resource Sharing – threads share resources of process, easier than shared memory or message passing Economy – cheaper than process creation, thread switching lower overhead than context switching Scalability – process can take advantage of multiprocessor architectures

10 4.10 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Why Threads? The primary motivation for using threads is to realize potential program performance gains When compared to the cost of creating and managing a process, a thread can be created with much less operating system overhead Managing threads requires fewer system resources than managing processes All threads within a process share the same address space Inter-thread communication is more efficient and in many cases, easier to use than inter-process communication.

11 4.11 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Why Threads? Threaded applications offer potential performance gains and practical advantages over non-threaded applications in ways: Overlapping CPU work with I/O:  For example, a program may have sections where it is performing a long I/O operation  While one thread is waiting for an I/O system call to complete, CPU intensive work can be performed by other threads Asynchronous event handling: tasks which service events of indeterminate frequency and duration can be interleaved For example, a web server can both transfer data from previous requests and manage the arrival of new requests

12 4.12 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Multithreaded Server Architecture

13 4.13 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition User Threads and Kernel Threads User threads - management done by user-level threads library Three primary thread libraries: POSIX Pthreads Windows threads Java threads Kernel threads - Supported by the Kernel Examples – virtually all general purpose operating systems, including: Windows Solaris Linux Tru64 UNIX Mac OS X

14 4.14 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Multithreading Models Many-to-One One-to-One Many-to-Many

15 4.15 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Many-to-One Many user-level threads mapped to single kernel thread One thread blocking causes all to block Multiple threads may not run in parallel on multicore system because only one may be in kernel at a time Few systems currently use this model Examples: Solaris Green Threads GNU Portable Threads

16 4.16 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition One-to-One Each user-level thread maps to kernel thread Creating a user-level thread creates a kernel thread More concurrency than many-to-one Number of threads per process sometimes restricted due to overhead Examples Windows Linux Solaris 9 and later

17 4.17 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Many-to-Many Model Allows many user level threads to be mapped to many kernel threads Allows the operating system to create a sufficient number of kernel threads Solaris prior to version 9 Windows with the ThreadFiber package

18 4.18 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Thread Libraries Thread library provides programmer with API for creating and managing threads Two primary ways of implementing Library entirely in user space Kernel-level library supported by the OS

19 4.19 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Pthreads May be provided either as user-level or kernel-level A POSIX standard (IEEE 1003.1c) API for thread creation and synchronization Specification, not implementation API specifies behavior of the thread library, implementation is up to development of the library Common in UNIX operating systems (Solaris, Linux, Mac OS X)

20 4.20 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Pthread Creation int pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg); Initially, your main() program comprises a single, default thread All other threads must be explicitly created by the programmer pthread_create creates a new thread and makes it executable Typically, threads are first created from within main() inside a single process Once created, threads are peers, and may create other threads

21 4.21 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition pthread_create arguments: thread: A unique identifier for the new thread returned by the subroutine attr: An attribute object that may be used to set thread attributes  You can specify a thread attributes object, or NULL for the default values start_routine: the C routine that the thread will execute once it is created  The routine must return a void * pointer (cast if necessary)  The routine must have at most one parameter, again a void * pointer  If the routine needs more than one argument, create some sort of structure (array, struct, etc), casting it to void * of course arg: A single argument that may be passed to start_routine  It must be passed by reference as a pointer cast of type void  NULL may be used if no argument is to be passed

22 4.22 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Passing arguments to threads The pthread_create() routine permits the programmer to pass one argument to the thread start routine For cases where multiple arguments must be passed: Create a structure which contains all of the arguments Pass a pointer to that structure in the pthread_create() routine All arguments must be passed by reference and cast to (void *)

23 4.23 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Thread Termination There are several ways in which a Pthread may be terminated: The thread returns from its starting routine (the main routine for the initial thread) The thread makes a call to the pthread_exit subroutine (covered below) The thread is canceled by another thread via the pthread_cancel routine (not covered here) The entire process is terminated due to a call to either the exec or exit subroutines

24 4.24 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition pthread_exit void pthread_exit(void *retval); pthread_exit is used to explicitly exit a thread Typically, the pthread_exit() routine is called after a thread has completed its work and is no longer required to exist If main() finishes before the threads it has created, and exits with pthread_exit(), the other threads will continue to execute Otherwise, they will be automatically terminated when main() finishes The programmer may optionally specify a termination status, which is stored as a void pointer for any thread that may join the calling thread

25 4.25 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition thread_ex1.c #include #include #include #define NUM_THREADS 5 void *PrintHello(void *threadid) { sleep(1); printf("\n%d: Hello World!\n", threadid); pthread_exit(NULL); } int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf("Creating thread %d\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } printf( "\nmain about to exit\n" ); pthread_exit(NULL); }

26 4.26 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition output > gcc thread_ex.c -lpthread >./a.out Creating thread 0 Creating thread 1 Creating thread 2 Creating thread 3 Creating thread 4 main about to exit 0: Hello World! 1: Hello World! 2: Hello World! 3: Hello World! 4: Hello World!

27 4.27 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition thread_ex2.c /* A program to demonstrate thread creation and exit Note: in this version, main does NOT do a thread_exit() so all other theads die with main To run: a.out */ #include #include #include #define NUM_THREADS 5 void *PrintHello(void *threadid) { sleep(1); printf("\n%d: Hello World!\n", threadid); pthread_exit(NULL); }

28 4.28 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition int main (int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int rc, t; for(t=0; t<NUM_THREADS; t++){ printf("Creating thread %d\n", t); rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\n", rc); exit(-1); } } printf( "\nmain about to exit\n" ); //Notice missing pthread_exit() statement }

29 4.29 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition output > gcc thread_ex2.c -lpthread >./a.out Creating thread 0 Creating thread 1 Creating thread 2 Creating thread 3 Creating thread 4 main about to exit

30 4.30 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition See thread_ex4.c Output >./a.out Creating thread 0 Creating thread 1 Creating thread 2 Thread 1: French: Bonjour, le monde! Creating thread 3 Creating thread 4 Thread 3: Klingon: Nuq neH! Creating thread 5 Creating thread 6 Thread 5: Russian: Zdravstvytye, mir! Creating thread 7 Thread 7: Latin: Orbis, te saluto! Thread 0: English: Hello World! Thread 2: Spanish: Hola al mundo Thread 4: Turkish: Merhaba dunya! Thread 6: Japan: Sekai e konnichiwa!

31 4.31 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition See thread_ex5.c

32 4.32 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Joining Threads int pthread_join(pthread_t th, void **thread_return); Suspends the execution of the calling thread until the thread identified by th terminates, either by calling pthread_exit or by being cancelled If thread_return is not NULL, the return value of th is stored in the location pointed to by thread_return  The return value of th is either the argument it gave to pthread_exit, or PTHREAD_CANCELED if th was cancelled The joined thread th must be in the joinable state:  It must not have been detached using pthread_detach or  The PTHREAD_CREATE_DETACHED attribute to pthread_create When a joinable thread terminates, its memory resources (thread descriptor and stack) are not deallocated until another thread performs pthread_join on it  Therefore, pthread_join must be called once for each joinable thread created to avoid memory leaks At most one thread can wait for the termination of a given thread  Calling pthread_join on a thread th on which another thread is already waiting for termination returns an error

33 4.33 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Detaching: int pthread_detach(pthread_t th); pthread_detach puts the thread th in the detached state This guarantees that the memory resources consumed by th will be freed immediately when th terminates However, this prevents other threads from synchronizing on the termination of th using pthread_join A thread can be created initially in the detached state, using the detachstate attribute to pthread_create In contrast, pthread_detach applies to threads created in the joinable state, and which need to be put in the detached state later There is no converse routine After pthread_detach completes, subsequent attempts to perform pthread_join on th will fail If another thread is already joining the thread th at the time pthread_detach is called, pthread_detach does nothing and leaves th in the joinable state

34 4.34 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition /* A program that demonstrates pthread create and join To run: a.out */ #include #include #include void *print_message_function( void *ptr ); main() { pthread_t thread1, thread2; char *message1 = "Thread 1"; char *message2 = "Thread 2"; int iret1, iret2; /* Create independant threads each of which will execute function */ iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1); iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2); /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ pthread_join( thread1, NULL); pthread_join( thread2, NULL); printf("Thread 1 returns: %d\n",iret1); printf("Thread 2 returns: %d\n",iret2); exit(0); }

35 4.35 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition void *print_message_function( void *ptr ) { char *message; message = (char *) ptr; printf("%s \n", message); }

36 4.36 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition >./a.out Thread 1 Thread 2 Thread 1 returns: 0 Thread 2 returns: 0

37 4.37 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Pthreads Example

38 4.38 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Pthreads Example (Cont.)

39 4.39 Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Pthreads Code for Joining 10 Threads


Download ppt "Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Chapter 4: Threads."

Similar presentations


Ads by Google