Professional Documents
Culture Documents
Ion Mandoiu
Laurent Michel
Revised by M. Khan and J. Shi
More Synchronization Primitives
• So far
• Mutexes
• Condition variables
• Today
• Read-write locks
• Barriers
• Fixed order
• All the threads lock mutexes in the same order
5
Solutions?
#include <pthread.h>
pthread_rwlock_t rwlock; // define a read-write lock
8
Pthread Read-Write Locks For Writing
9
Read-Write Lock Issues
• Writer starvation
• Too many readers. Writers do not have a chance to start
• Solution?
• "write locks shall take precedence over read locks"
• which leads to reader starvation
10
Pthread read-write lock
11
Use mutex and condition to implement rwlock
• Using mutex and condition is more flexible, we can adjust our strategy
• There are many ways
http://heather.cs.ucdavis.edu/~matloff/158/PLN/RWLock.c
12
Pseudocode for rwlock lock
pthread_mutex_lock(&mutex);
// increment/decrement waiting counter and the while loop
increment waiting counter
// predicate depends on the policy!
while (! predicate) // check if this thread can lock
pthread_cond_wait(&cond); // using either rd or wr condition
decrement waiting counter
increment active counter
pthread_mutex_unlock(&mutex);
// rwlock is locked. Can start to read/write
// Note that mutex is unlocked!
13
Pseudocode for rwlock unlock
14
Example: rwlock_writeunlock()
Does this lock prefer reader or writer? A: reader B: writer C: don't know
• Purpose
• For applications where work is done in “phases”
• Must have “worker” threads wait for the entire “group” to be done before
proceeding to next phase
• Number of workers known a priori
16
Visually
T1
T2
T3
T4
T5
5 17
Visually
T1
T2
T3
T4
T5
5 18
Visually
T1
T2
T3
T4
T5 Zzzz…
5 19
Visually
T1
T2 Zzzz…
T3 Zzzz…
T4
T5 Zzzz…
5 20
Visually
T1
T2 Zzzz…
T3 Zzzz…
T4 Zzzz…
T5 Zzzz…
5 21
Visually
T1
T2 Zzzz…
T3 Zzzz…
T4 Zzzz…
T5 Zzzz…
5 22
Visually
5 Last one
notifies!
T1
T2 Zzzz…
T3 Zzzz…
T4 Zzzz…
T5 Zzzz…
5 23
Reusable Barrier?
T1
T2 Wakeup…
T3 Wakeup…
T4 Wakeup…
T5 Wakeup…
24
POSIX Barriers Support
#include <pthread.h>
// create barrier. note the count argument
int pthread_barrier_init(pthread_barrier_t *restrict barrier,
const pthread_barrierattr_t *restrict attr, unsigned count);
// destroy a barrier
int pthread_barrier_destroy(pthread_barrier_t *barrier);
25
Sync mechanisms in this course
• We can use mutex, condition, read/write lock, barriers, and only call
blocking functions!
26