Principles of Operating Systems Lecture 8

Slides:



Advertisements
Similar presentations
CS Lecture 4 Programming with Posix Threads and Java Threads George Mason University Fall 2009.
Advertisements

Pthreads & Concurrency. Acknowledgements  The material in this tutorial is based in part on: POSIX Threads Programming, by Blaise Barney.
Professor: Shu-Ching Chen TA: Hsin-Yu Ha.  An independent stream of instructions that can be scheduled to run  A path of execution int a, b; int c;
PTHREADS These notes are from LLNL Pthreads Tutorial
Computer Architecture II 1 Computer architecture II Programming: POSIX Threads OpenMP.
Fork Fork is used to create a child process. Most network servers under Unix are written this way Concurrent server: parent accepts the connection, forks.
Pthreads Operating Systems Hebrew University of Jerusalem Spring 2004.
B.Ramamurthy1 POSIX Thread Programming 2/14/97 B.Ramamurthy.
Unix Threads operating systems. User Thread Packages pthread package mach c-threads Sun Solaris3 UI threads Kernel Threads Windows NT, XP operating systems.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Silberschatz, Galvin and Gagne ©2013 Operating System Concepts Essentials – 9 th Edition Chapter 4: Threads.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 4: Threads Changes by MA Doman 2013.
PRINCIPLES OF OPERATING SYSTEMS Lecture 6: Processes CPSC 457, Spring 2015 May 21, 2015 M. Reza Zakerinasab Department of Computer Science, University.
CGS 3763 Operating Systems Concepts Spring 2013 Dan C. Marinescu Office: HEC 304 Office hours: M-Wd 11: :30 AM.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
Operating Systems CMPSC 473 Multi-threading models Tutorial on pthreads Lecture 10: September Instructor: Bhuvan Urgaonkar.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
POSIX Threads Programming Operating Systems. Processes and Threads In shared memory multiprocessor architectures, such as SMPs, threads can be used to.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
Professor: Shu-Ching Chen TA: Samira Pouyanfar.  An independent stream of instructions that can be scheduled to run  A path of execution int a, b; int.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
Pthreads.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
Unix Internals Concurrent Programming. Unix Processes Processes contain information about program resources and program execution state, including: Process.
CSC 360, Instructor: Kui Wu Thread & PThread. CSC 360, Instructor: Kui Wu Agenda 1.What is thread? 2.User vs kernel threads 3.Thread models 4.Thread issues.
Threads A thread is an alternative model of program execution
NCHU System & Network Lab Lab #6 Thread Management Operating System Lab.
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
PRINCIPLES OF OPERATING SYSTEMS Tutorial-4: Multi-process and Multi-threaded Programming CPSC 457, Spring 2015 May 28/29, 2015 Department of Computer Science,
POSIX THREADS. What is a thread? Multiple stands of execution in a single program are called threads. In other words, a thread is a sequence of control.
Thread Programming 김 도 형김 도 형. 2 Table of Contents  What is a Threads?  Designing Threaded Programs  Synchronizing Threads  Managing Threads.
B. RAMAMURTHY 5/10/2013 Amrita-UB-MSES Realizing Concurrency using the thread model.
7/9/ Realizing Concurrency using Posix Threads (pthreads) B. Ramamurthy.
Tutorial 4. In this tutorial session we’ll see Threads.
A thread is a basic unit of CPU utilization within a process Each thread has its own – thread ID – program counter – register set – stack It shares the.
Realizing Concurrency using the thread model
Lesson One – Creating a thread
Realizing Concurrency using the thread model
PThreads.
Principles of Operating Systems Lecture 11
Threads in C Caryl Rahn.
Threads Threads.
Boost String API & Threads
Copyright ©: Nahrstedt, Angrave, Abdelzaher
Thread Programming.
Chapter 4: Threads.
PTHREADS These notes are from LLNL Pthreads Tutorial
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using Posix Threads (pthreads)
Operating Systems Lecture 13.
CSE 333 – Section 9 Threads.
Realizing Concurrency using the thread model
Lecture 8: POSIX Threads
PTHREADS AND SEMAPHORES
Multithreading Tutorial
Thread Programming.
Realizing Concurrency using the thread model
Pthread Prof. Ikjun Yeom TA – Mugyo
Multithreading Tutorial
Multithreading Tutorial
Realizing Concurrency using the thread model
Realizing Concurrency using Posix Threads (pthreads)
Realizing Concurrency using the thread model
Lecture 9: POSIX Threads Cont.
Realizing Concurrency using Posix Threads (pthreads)
Lecture 8: POSIX Threads
Tutorial 4.
Shared Memory Programming with Pthreads
POSIX Threads(pthreads)
Presentation transcript:

Principles of Operating Systems Lecture 8 Abhishek Dubey Daniel Balasubramanian Pthreads Slides based on https://computing.llnl.gov/tutorials/pthreads/ Spring 2014

Pthreads The IEEE POSIX ‘C’ specification for threading interface. Various operating systems implement these interfaces. All symbols and functions described in ‘pthreads.h’ http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread.h.html

Pthreads Thread Management pthread_create: create a new thread. The newly created thread can be in one of the two states Detatched Release the resources of thread immediately when it terminates pthread_detach: make the thread detached Joinable Some other thread will call pthread_join to know the status of the thread. pthread_join: Find out the return value of the thread function. Similar to wait. But supports timeouts. pthread_cancel: cancel an existing thread. pthread_exit: terminate the calling thread.

Thread creation 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. This routine can be called any number of times from anywhere within your code. pthread_create arguments: thread: An opaque, unique identifier for the new thread returned by the subroutine. attr: An opaque 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. 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. The maximum number of threads that may be created by a process is implementation dependent. Programs that attempt to exceed the limit can fail or produce wrong results. Once created, threads are peer. There is no hierarchy among threads.

Thread Attributes: By default, a thread is created with certain attributes. Some of these attributes can be changed by the programmer via the thread attribute object. pthread_attr_init and pthread_attr_destroy are used to initialize/destroy the thread attribute object. Other routines are then used to query/set specific attributes in the thread attribute object. Attributes include: Detached or joinable state Scheduling inheritance Scheduling policy Scheduling parameters Scheduling contention scope Stack size Stack address

Terminating threads There are several ways in which a thread may be terminated: The thread returns normally from its starting routine. It's work is done. The thread makes a call to the pthread_exit subroutine - whether its work is done or not. The thread is canceled by another thread via the pthread_cancel routine. The entire process is terminated due to making a call to either the exec() or exit() If main() finishes first, without calling pthread_exit explicitly itself

Example

pthread_exit In subroutines that execute to completion normally, you can often dispense with calling pthread_exit() - unless, of course, you want to pass the optional status code back. Cleanup: the pthread_exit() routine does not close files; any files opened inside the thread will remain open after the thread is terminated. Discussion on calling pthread_exit() from main(): There is a definite problem if main() finishes before the threads it spawned if you don't call pthread_exit() explicitly. All of the threads it created will terminate because main() is done and no longer exists to support the threads. By having main() explicitly call pthread_exit() as the last thing it does, main() will block and be kept alive to support the threads it created until they are done.

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, this limitation is easily overcome by creating a structure which contains all of the arguments, and then passing a pointer to that structure in the pthread_create() routine. All arguments must be passed by reference and cast to (void *).

Example

Joining and detaching threads Joining is a way to accomplish synchronization between threads The pthread_join() subroutine blocks the calling thread until the specified threadid thread terminates. The programmer is able to obtain the target thread's termination return status if it was specified in the target thread's call to pthread_exit(). A joining thread can match one pthread_join() call. It is a logical error to attempt multiple joins on the same thread. https://computing.llnl.gov/tutorials/pthreads/#PassingArguments

More on joining thread When a thread is created, one of its attributes defines whether it is joinable or detached. Only threads that are created as joinable can be joined. If a thread is created as detached, it can never be joined. To explicitly create a thread as joinable or detached, the attr argument in the pthread_create() routine is used. The typical 4 step process is: Declare a pthread attribute variable of the pthread_attr_t data type Initialize the attribute variable with pthread_attr_init() Set the attribute detached status with pthread_attr_setdetachstate() When done, free library resources used by the attribute with pthread_attr_destroy() The pthread_detach() routine can be used to explicitly detach a thread even though it was created as joinable. There is no converse routine. Recommendations: If a thread requires joining, consider explicitly creating it as joinable. This provides portability as not all implementations may create threads as joinable by default. If you know in advance that a thread will never need to join with another thread, consider creating it in a detached state. Some system resources may be able to be freed.

Join Example

Pthread cancel Cancel execution of a thread The pthread_cancel() function shall request that thread be canceled. Thread’s cancelation depends upon The cancelability state of the thread If the thread is in a library method that is a cancellation point.

Thread cancelability state 1/2 int pthread_setcancelstate(int state, int *oldstate); The pthread_setcancelstate() sets the cancelability state of the calling thread to the value given in state. The previous cancelability state of the thread is returned in the buffer pointed to by oldstate. The state argument must have one of the following values: PTHREAD_CANCEL_ENABLE The thread is cancelable. This is the default cancelability state in all new threads, including the initial thread. The thread's cancelability type determines when a cancelable thread will respond to a cancellation request. PTHREAD_CANCEL_DISABLE The thread is not cancelable. If a cancellation request is received, it is blocked until cancelability is enabled.

Thread cancelability state 1/2 int pthread_setcancelstate(int state, int *oldstate); The pthread_setcancelstate() sets the cancelability state of the calling thread to the value given in state. The previous cancelability state of the thread is returned in the buffer pointed to by oldstate. The state argument must have one of the following values: PTHREAD_CANCEL_ENABLE The thread is cancelable. This is the default cancelability state in all new threads, including the initial thread. The thread's cancelability type determines when a cancelable thread will respond to a cancellation request. PTHREAD_CANCEL_DISABLE The thread is not cancelable. If a cancellation request is received, it is blocked until cancelability is enabled.

Thread cancelability state 1/2 int pthread_setcanceltype(int type, int *oldtype); The pthread_setcanceltype() sets the cancelability type of the calling thread to the value given in type. The previous cancelability type of the thread is returned in the buffer pointed to by oldtype. The type argument must have one of the following values: PTHREAD_CANCEL_DEFERRED A cancellation request is deferred until the thread next calls a function that is a cancellation point. This is the default cancelability type in all new threads, including the initial thread. PTHREAD_CANCEL_ASYNCHRONOUS The thread can be canceled at any time. (Typically, it will be canceled immediately upon receiving a cancellation request, but the system doesn't guarantee this.)

Cancellation points POSIX.1 specifies that certain functions must, and certain other functions may, be cancellation points. If a thread is cancelable, its cancelability type is deferred, and a cancellation request is pending for the thread, then the thread is canceled when it calls a function that is a cancellation point. Example Close Sleep … For more details look http://man7.org/linux/man-pages/man7/pthreads.7.html

Thread cleanup handlers void pthread_cleanup_pop(int execute); void pthread_cleanup_push(void (*routine)(void*), void *arg); The pthread_cleanup_pop() function shall remove the routine at the top of the calling thread's cancellation cleanup stack and optionally invoke it (if execute is non-zero). The pthread_cleanup_push() function shall push the specified cancella- tion cleanup handler routine onto the calling thread's cancellation cleanup stack. The cancellation cleanup handler shall be popped from the cancellation cleanup stack and invoked with the argument arg when: The thread exits (that is, calls pthread_exit()). The thread acts upon a cancellation request. The thread calls pthread_cleanup_pop() with a non-zero execute argument.

Cleanup example