- Pthread Synchronization
Operating Systems Hebrew University Spring 2004
What’s the problem
Process thread1 { foo = 1; bar = 2; } Process thread2 { foo = 3; bar = 4; }
- What are the possible results?
Race condition
- Two threads racing to perform the same
task
- Interleaving of operations can cause
incorrect behavior
Atomic Updates
- Perform the following items as a single unit
- When we are done, exactly (A or B) is true
– not (A and B) – not part of A and part of B
- Critical Section!
Mutex
- Enter and Exit critical
section
#include <pthread.h> int pthread_mutex_lock(mutex); int pthread_mutex_unlock(mutex);
mutex_var Thread A Thread B
lock block
var
access
No problem
Process thread1 { pthread_mutex_lock(l); foo = 1; bar = 2; pthread_mutex_unlock(l); } Process thread2 { pthread_mutex_lock(l); foo = 3; bar = 4; pthread_mutex_unlock(l); }
- What are the possible results?