mutex:http://www.cplusplus.com/reference/mutex/mutex/?kw=mutex
lock_guard:http://www.cplusplus.com/reference/mutex/lock_guard/?kw=lock_guard
class
<mutex>
std::mutex
class mutex;
Mutex class
A mutex is a lockable object that is designed to signal when critical sections of code need exclusive access, preventing other threads with the same protection from executing concurrently and access the same memory locations.
mutex objects provide exclusive ownership and do not support recursivity (i.e., a thread shall not lock a mutex it already owns) -- see recursive_mutex for an alternative class that does.
It is guaranteed to be a standard-layout class.
Member types
member type | description |
---|---|
native_handle_type | Type returned by native_handle (only defined if library implementation supports it) |
Member functions
Construct mutex (public member function )
Lock mutex (public member function )
Lock mutex if not locked (public member function )
Unlock mutex (public member function )
Get native handle (public member function )
Example
| |
Possible output (order of lines may vary, but characters are never mixed):
************************************************** $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
|
class template
<mutex>
std::lock_guard
template <class Mutex> class lock_guard;
Lock guard
A lock guard is an object that manages a mutex object by keeping it always locked.
On construction, the mutex object is locked by the calling thread, and on destruction, the mutex is unlocked. It is the simplest lock, and is specially useful as an object with automatic duration that lasts until the end of its context. In this way, it guarantees the mutex object is properly unlocked in case an exception is thrown.
Note though that the lock_guard object does not manage the lifetime of the mutex object in any way: the duration of the mutex object shall extend at least until the destruction of the lock_guard that locks it.
Template parameters
Mutex
A mutex-like type.
It shall be a basic lockable type, such as mutex (see BasicLockable for requirements).
Member types
member type | definition | description |
---|---|---|
mutex_type | The template parameter (Mutex) | The managed mutex object type |
Member functions
Construct lock_guard (public member function )
Destroy lock_guard (unlocking mutex) (public member function )
Example
| |
Possible output:
[exception caught] 2 is even [exception caught] 4 is even [exception caught] 6 is even [exception caught] 8 is even [exception caught] 10 is even |
The order of the lines printed may be different.