From Threads Primer
Mutex, Semaphore, Condition variable
Mutex, Semaphore, Condition variable
Mutex: Mutual exclusion lock is the simplest and most primitive synchronization variable. The first thread that locks the mutex gets ownership, and any subsequent attempts to lock it will fail, causing the calling thread to go to sleep.
Using Mutexes in the Different Libraries:
POSIX
pthread_mutex_lock(m)
...
pthread_mutex_unlock(m)
Win32
WaitForSingleObject(m)
...
ReleaseMutex(m)
Using Mutexes in the Different Libraries:
POSIX
pthread_mutex_lock(m)
...
pthread_mutex_unlock(m)
Win32
WaitForSingleObject(m)
...
ReleaseMutex(m)
Semaphore: A counting semaphore is a variable that you can increment arbitrarily high, but decrement only to zero. If the semaphore is greater than zero, the operation succeeds; if not, then the calling thread must go to sleep until a different thread increments it. A semaphore is useful for working with "train-like" objects, that is, objects where what you care about is whether there are either zero objects or more than zero. A semaphore is perfect for situations where you want to count things and have threads sleep when some limit is hit. A typical example is producer/consumer application.
Condition variable: The programmer is responsible for locking and unlocking the mutex, testing and changing the condition, and waking up sleepers. Otherwise, it is exactly like a semaphore. It works like this: A thread obtains a mutex and tests the condition under the mutex's protection. No other thread should alther any aspect of the condition without holding the mutex. If the condition is ture, your thread completes its task, relaesing the mutex when appropriate. If the condition is NOT true, the mutex is released for you, and your thread goes to sleep on the condition variable.
No comments:
Post a Comment