Pthread (continue) General pthread program structure –Encapsulate parallel parts (can be almost the whole program) in functions. –Use function arguments.

Slides:



Advertisements
Similar presentations
Operating Systems Semaphores II
Advertisements

1 Interprocess Communication 1. Ways of passing information 2. Guarded critical activities (e.g. updating shared data) 3. Proper sequencing in case of.
Synchronization and Deadlocks
Chapter 6: Process Synchronization
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores.
Multi-core Programming Programming with Posix Threads.
5.6 Semaphores Semaphores –Software construct that can be used to enforce mutual exclusion –Contains a protected variable Can be accessed only via wait.
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
Lecture 18 Threaded Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger.
Monitors CSCI 444/544 Operating Systems Fall 2008.
Semaphores CSCI 444/544 Operating Systems Fall 2008.
Threads© Dr. Ayman Abdel-Hamid, CS4254 Spring CS4254 Computer Network Architecture and Programming Dr. Ayman A. Abdel-Hamid Computer Science Department.
Race Conditions CS550 Operating Systems. Review So far, we have discussed Processes and Threads and talked about multithreading and MPI processes by example.
U NIVERSITY OF M ASSACHUSETTS, A MHERST Department of Computer Science Emery Berger University of Massachusetts, Amherst Operating Systems CMPSCI 377 Lecture.
Comp 422: Parallel Programming Shared Memory Multithreading: Pthreads Synchronization.
CS 241 Section Week #4 (2/19/09). Topics This Section  SMP2 Review  SMP3 Forward  Semaphores  Problems  Recap of Classical Synchronization Problems.
Synchronization Andy Wang Operating Systems COP 4610 / CGS 5765.
Semaphores. Readings r Silbershatz: Chapter 6 Mutual Exclusion in Critical Sections.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
The University of Adelaide, School of Computer Science
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Introduction to Concurrency.
Multi-threaded Programming with POSIX Threads CSE331 Operating Systems Design.
Threads and Thread Control Thread Concepts Pthread Creation and Termination Pthread synchronization Threads and Signals.
Copyright ©: University of Illinois CS 241 Staff1 Synchronization and Semaphores.
ICS 145B -- L. Bic1 Project: Process/Thread Synchronization Textbook: pages ICS 145B L. Bic.
CS345 Operating Systems Threads Assignment 3. Process vs. Thread process: an address space with 1 or more threads executing within that address space,
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Semaphore and Mutex Operations.
Programming with POSIX* Threads Intel Software College.
COMP 111 Threads and concurrency Sept 28, Tufts University Computer Science2 Who is this guy? I am not Prof. Couch Obvious? Sam Guyer New assistant.
Operating Systems ECE344 Ashvin Goel ECE University of Toronto Mutual Exclusion.
11/18/20151 Operating Systems Design (CS 423) Elsa L Gunter 2112 SC, UIUC Based on slides by Roy Campbell, Sam.
Chapter 7 -1 CHAPTER 7 PROCESS SYNCHRONIZATION CGS Operating System Concepts UCF, Spring 2004.
Pthreads: A shared memory programming model
Threads and Locking Ioctl operations. Threads Lightweight processes What’s wrong with processes? –fork() is expensive – 10 to 100 times slower –Inter.
Threads Chapter 26. Threads Light-weight processes Each process can have multiple threads of concurrent control. What’s wrong with processes? fork() is.
1 Pthread Programming CIS450 Winter 2003 Professor Jinhua Guo.
POSIX Synchronization Introduction to Operating Systems: Discussion Module 5.
Synchronizing Threads with Semaphores
Threads Tutorial #7 CPSC 261. A thread is a virtual processor Each thread is provided the illusion that it owns a core – Copy of the registers – It is.
1 CMSC421: Principles of Operating Systems Nilanjan Banerjee Principles of Operating Systems Acknowledgments: Some of the slides are adapted from Prof.
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 11: Thread-safe Data Structures, Semaphores.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Software Systems Advanced Synchronization Emery Berger and Mark Corner University.
CS399 New Beginnings Jonathan Walpole. 2 Concurrent Programming & Synchronization Primitives.
1 Synchronization Threads communicate to ensure consistency If not: race condition (non-deterministic result) Accomplished by synchronization operations.
1 Condition Variables CS 241 Prof. Brighten Godfrey March 16, 2012 University of Illinois.
Chapter 6 P-Threads. Names The naming convention for a method/function/operation is: – pthread_thing_operation(..) – Where thing is the object used (such.
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 13: Condition Variable, Read/Write Lock, and Deadlock.
U NIVERSITY OF M ASSACHUSETTS A MHERST Department of Computer Science Computer Systems Principles Synchronization Emery Berger and Mark Corner University.
PThread Synchronization. Thread Mechanisms Birrell identifies four mechanisms commonly used in threading systems –Thread creation –Mutual exclusion (mutex)
Thread Basic Thread operations include thread creation, termination, synchronization, data management Threads in the same process share:  Process address.
Working with Pthreads. Operations on Threads int pthread_create (pthread_t *thread, const pthread_attr_t *attr, void * (*routine)(void*), void* arg) Creates.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
pThread synchronization
Case Study: Pthread Synchronization Dr. Yingwu Zhu.
Synchronization and Semaphores
Background on the need for Synchronization
PThreads.
Threads Threads.
Thread synchronization
Andy Wang Operating Systems COP 4610 / CGS 5765
Lecture 14: Pthreads Mutex and Condition Variables
Concurrency: Mutual Exclusion and Process Synchronization
CSE 451: Operating Systems Autumn Lecture 8 Semaphores and Monitors
Lecture 14: Pthreads Mutex and Condition Variables
CSE 153 Design of Operating Systems Winter 2019
CS333 Intro to Operating Systems
Lecture 20: Synchronization
CS 144 Advanced C++ Programming May 7 Class Meeting
POSIX Threads(pthreads)
Presentation transcript:

Pthread (continue) General pthread program structure –Encapsulate parallel parts (can be almost the whole program) in functions. –Use function arguments to parameterize what a particular thread does. Usually needs to know myid and nprocs. Add synchronization when necessary –Call pthread_create() with the function and arguments, save thread identifier returned. –Call pthread_join() with that thread identifier

Thread synchronizations When more than one thread works on the same task, the threads often need to coordinate their activities to ensure correct behavior. –Coordination that results in synchronization or communication is the inherent price to pay when going multithreading. Coordination often means waiting!

Motivating Example: Too Much Milk Two robots are programmed to maintain the milk inventory at a store… They are not aware of each other’s presence… Robot: Dumb Robot: Dumber

Motivating Example: Too Much Milk Dumb 4:00Look into fridge: Out of milk Dumber

Motivating Example: Too Much Milk Dumb 4:00Look into fridge: Out of milk 4:05Head for the warehouse Dumber

Motivating Example: Too Much Milk Dumb 4:05Head for the warehouse Dumber 4:10Look into fridge: Out of milk

Motivating Example: Too Much Milk DumbDumber 4:10Look into fridge: Out of milk 4:15 Head for the warehouse

Motivating Example: Too Much Milk Dumb 4:20Arrive with milk Dumber 4:15 Head for the warehouse

Motivating Example: Too Much Milk Dumb 4:20Arrive with milk Dumber 4:15 Head for the warehouse

Motivating Example: Too Much Milk Dumb 4:20Arrive with milk 4:25Go party Dumber

Motivating Example: Too Much Milk Dumb 4:20Arrive with milk 4:25Go party Dumber 4:30Arrive with milk: “Uh oh…”

Common coordination constructs Critical section: a piece of code that only one thread can execute at a time –Only one thread can go get milk at one time. Mutual exclusion: ensure one thread can do something without the interference of other threads –When I print, nobody else should be printing.

Common coordination constructs Synchronization: use atomic operations to ensure cooperation among threads –Event synchronization T1 T2 … X = 400 Y = X+1 …... T1 T2 … X = 400 …. X ready … wait for X Y=X+1 …...

Pthreads synchronization support Mutex locks –Critical session and mutual exclusion Condition variables –Event synchronization Semaphores –Both (in UNIX, not pthread)

Mutex locks: lock/unlock pthread_mutex_lock(pthread_mutex_t *mutex); –Tries to acquire the lock specified by mutex –If mutex is already locked, then the calling thread blocks until mutex is unlocked. At one time, only one thread can get the lock

Mutex locks: lock/unlock pthread_mutex_unlock(pthread_mutex_t *mutex); –If the calling thread has mutex currently locked, this will unlock the mutex. –If other threads are blocked waiting on this mutex, one will unblock and acquire mutex. –Which one is determined by the scheduler.

Lock and critical section A lock prevents a thread from doing something –A thread should lock before entering a critical section –A thread should unlock when leaving the critical section –A thread should wait if the critical section is locked Synchronization often involves waiting

Mutex lock– for mutual exclusion int counter = 0; void *thread_func(void *arg) { int val; /* unprotected code – why? */ val = counter; counter = val + 1; return NULL; }

Mutex example int counter = 0; ptread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_func(void *arg) { int val; /* protected by mutex */ Pthread_mutex_lock( &mutex ); val = counter; counter = val + 1; Pthread_mutex_unlock( &mutex ); return NULL; }

Condition variables – and event synchronization Think of Producer – consumer problem Producers and consumers run in separate threads. Producer produces data and consumer consumes data. Producer has to inform the consumer when data is available Consumer has to inform producer when buffer space is available

Condition variables: wait Pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex) –Blocks the calling thread, waiting on cond. –Unlock the mutex –Re-acquires the mutex when unblocked.

Condition variables: signal Pthread_cond_signal(pthread_cond_t *cond) –Unblocks one thread waiting on cond. –The scheduler determines which thread to unblock. –If no thread waiting, then signal is a no-op

Producer consumer program without condition variables

/* Globals */ int data_avail = 0; pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER; void *producer(void *) { Pthread_mutex_lock(&data_mutex); Produce data Insert data into queue; data_avail=1; Pthread_mutex_unlock(&data_mutex); }

void *consumer(void *) { while( !data_avail ); /* do nothing – keep looping!!*/ Pthread_mutex_lock(&data_mutex); Extract data from queue; if (queue is empty) data_avail = 0; Pthread_mutex_unlock(&data_mutex); consume_data(); }

Producer consumer with condition variables

int data_avail = 0; pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cont_t data_cond = PTHREAD_COND_INITIALIZER; void *producer(void *) { Pthread_mutex_lock(&data_mutex); Produce data Insert data into queue; data_avail = 1; Pthread_cond_signal(&data_cond); Pthread_mutex_unlock(&data_mutex); }

void *consumer(void *) { Pthread_mutex_lock(&data_mutex); while( !data_avail ) { /* sleep on condition variable*/ Pthread_cond_wait(&data_cond, &data_mutex); } /* woken up */ Extract data from queue; if (queue is empty) data_avail = 0; Pthread_mutex_unlock(&data_mutex); consume_data(); }

A note on condition variables A signal is forgotten if there is no corresponding wait that has already occurred. If you want the signal to be remembered, use semaphores.

Semaphores Counters for resources shared between threads. Sem_wait(sem_t *sem) –Blocks until the semaphore vale is non-zero –Decrements the semaphore value on return. Sem_post(sem_t *sem) –Unblocks the semaphore and unblocks one waiting thread –Increments the semaphore value otherwise

Pipelined task parallelism with semaphore P1: for (I=0; I<num_pics, read(in_pic); I++) { int_pic_1[I] = trans1(in_pic); sem_post(event_1_2[I]); } P2: for (I=0; I<num_pics; I++) { sem_wait(event_1_2[I]); int_pic_2[I] = trans2(int_pic_1[I]); sem_post(event_2_3[I]); }

Challenges with thread programming Race condition: occurs when multiple threads and write to the same memory location. –Solution with a coordination mechanism: lock, conditional variable, semaphore, etc Coordination results in waiting among threads –Deadlocks: occur when threads are waiting for resources with circular dependencies

Deadlock example T1: T2: … Lock(printer) lock(keyboard) … Lock (keyboard) lock(printer) … Unlock(keyboard) unlock(printer) … Unlock(printer) unlock(keyboard)

Deadlock and third party software In sequence programs, using third party software is trivial. –Call “system(“/usr/bin/ls”); –No knowledge about /usr/bin/ls is needed. Could deadlock happen in thread programming by calling a third party program? –This is a big problem facing multi-thread programming.

Summary What is thread coordination (synchronization)? Why? What are the common thread coordinations? Pthread’s support for thread coordination. –Mutex lock –Condition variable Deadlock Thread programming issues