"Lecture 14: Pthreads Mutex and Condition Variables" is the property of its rightful owner. Permission is granted to
download and print the materials on this website for personal, non-commercial use only, and to display it
on your personal computer provided you do not modify the materials and that you retain all copyright
notices contained in the materials. By downloading content from our website, you accept the terms of this
agreement.
Share
Embed code
Presentation Transcript
01
Lecture 14: Pthreads Mutex and Condition Variables 1<br>
3 Review: Semaphore Implementation down(&S):
If (S=0) then
Suspend thread, put into a waiting queue
Schedule another thread to run
Else decrement S and return
up(&S):
Increment S
If any threads in waiting queue, then
release one of them (make it ‘ready’)
Both the above are done atomically
by disabling interrupts
by TSL/XCHG<br>
04
In this lecture Pthreads APIs
Mutex
Condition variables 4<br>
05
Some Pthreads APIs for mutex 5<br>
06
6 Mutex usage in POSIX Threads pthread_mutex_t m;
pthread_mutex_init(&m);
pthread_mutex_lock(&m);
critical_region();
pthread_mutex_unlock(&m);<br>
07
pthread_mutex_trylock Return fails when the mutex is already locked
Used for implementing busy waiting 7<br>
08
Mutex vs condition variables Mutex is good to guarantee mutual exclusion
Allow and block access to the critical regions
Conditional variables
Block threads due to some condition not met 8<br>
09
9 Condition Variables Allows a thread to wait till a condition is satisfied
Testing the condition must be done within a mutex
With every condition variable, a mutex is associated<br>
10
Pthreads APIs for condition variables 10<br>
11
Comparison with Semaphores If a signal is sent to a conditional variable on which no thread is waiting, the signal is lost
Semaphore will accumulate ‘signals’ by up() 11<br>
12
12 Condition Variables Waiting Thread:
pthread_mutex_lock(&mutex);
while (condition not satisfied) {
pthread_cond_wait( &condition_variable, &mutex);}
pthread_mutex_unlock(&mutex); Signaling Thread:
pthread_mutex_lock(&mutex);
/* change variable value */
if (condition satisfied) {
pthread_cond_signal( &condition_variable);
}
pthread_mutex_unlock(&mutex);
/* Alternative to cond_signal is
pthread_cond_broadcast( &condition_variable);
*/ pthread_cond_t condition_variable;
pthread_mutex_t mutex;<br>
13
13 Condition variable and mutex A mutex is passed into wait:pthread_cond_wait(cond_var, mutex)
Mutex is unlocked before the thread sleeps
Mutex is locked again before pthread_cond_wait() returns
Safe to use pthread_cond_wait() in a while loop and check condition again before proceeding<br>
14
14 Example Usage Write a program using two threads
Thread 1 prints “hello”
Thread 2 prints “world”
Thread 2 should wait till thread 1 finishes before printing
Use a condition variable<br>
15
15 Using condition variables int thread1_done = 0;
pthread_cond_t cv; pthread_mutex_t mutex; Thread 1: