Mutex Concept
The mutexes and locks here have simple interfaces that are designed for high performance. The interfaces enforce the scoped locking pattern, which is widely used in C++ libraries because:
It does not require the programmer to remember to release the lock.
It releases the lock if an exception is thrown out of the mutual exclusion region protected by the lock.
There are two parts to the pattern: a mutex and a lock. The constructor of the lock object acquires the lock, and the destructor of the lock object releases the lock. Here’s an example:
{
// Construction of myLock acquires lock on myMutex
M::scoped_lock myLock( myMutex );
... actions to be performed while holding the lock ...
// Destruction of myLock releases lock on myMutex
}If the actions throw an exception, the lock is automatically released as the block is exited.
Table 7-2 summarizes the classes that model the Mutex Concept.
Table 7-2. Mutex Concept
|
Pseudosignature |
Semantics |
|---|---|
|
|
Construct unlocked mutex. |
|
|
Destroy unlocked mutex. |
|
|
Construct lock without acquiring mutex. |
|
|
Construct lock and acquire lock on mutex. |
|
|
Release lock (if acquired). |
|
|
Acquire lock on mutex. |
|
|
Release lock. |