- When the semaphore's ability to count is not needed, a simplified version of the semaphore, called a mutex, is sometimes used.
- A mutex is a variable that can be in one of two states: unlocked or locked. Two procedures are used with mutexes.
- When a thread (or process) needs access to a critical region, it calls .
- If the mutex is current unlocked (meaning that the critical region is available), the call succeeds and the calling thread is free to enter the critical region.
Figure 4:
Some of the Pthreads calls relating to the mutexes.
|
Figure 5:
Using threads to solve the producer-consumer problem.
|
- On the other hand, if the mutex is already locked, the calling thread is blocked until the thread in the critical region is finished and calls .
- If multiple threads are blocked on the mutex, one of them is chosen at random and allowed to acquire the lock.
- With threads, there is no clock that stops threads that have run too long. Consequently, a thread that tries to acquire a lock by busy waiting will loop forever and never acquire the lock because it never allows any other thread to run and release the lock.
- That is where the difference between and comes in. When the later fails to acquire a lock, it calls to give up the CPU to another thread.
- Consequently there is no busy waiting. When the thread runs the next time, it tests the lock again.
Cem Ozdogan
2010-04-06