mutex Thread Synchronization (C++)
std::mutex
(C++)
The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.
Mutex
Mutex as the name hints implies mutual exclusion. A mutex is used to guard shared data such as a linked-list, an array or any simple primitive type. A mutex allows only a single thread to access a resource.
First saw this with the Singleton pattern.
I am seeing this in NVIDIA codebase.
Resources
- https://cplusplus.com/reference/mutex/mutex/
- https://en.cppreference.com/w/cpp/thread/mutex
- https://www.geeksforgeeks.org/multithreading-in-cpp/
Locking functions:
lock
: locks the mutex, blocks if the mutex is not available, see lock (C++)try_lock
: tries to lock the mutex, returns if the mutex is not availableunlock
: unlocks the mutex
You need to include the <mutex>
library to use this functionality
An example
Use a Lock
It is best practice to wrap these mutexes in a lock (C++) which employ RAII, and ensures the mutexes are unlocked when exiting.
Some more advanced mutexes in C++:
shared_time_mutex
shared_time_mutex
It’s shared_mutex
+ timed_mutex
shared_mutex
: https://en.cppreference.com/w/cpp/thread/shared_mutex
timed_mutex
: https://en.cppreference.com/w/cpp/thread/timed_mutex
The shared_timed_mutex
class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. In contrast to other mutex types which facilitate exclusive access, a shared_timed_mutex has two levels of access:
- exclusive - only one thread can own the mutex.
- shared - several threads can share ownership of the same mutex.
Shared mutexes are usually used in situations when multiple readers can access the same resource at the same time without causing data races, but only one writer can do so.
https://en.cppreference.com/w/cpp/thread/shared_timed_mutex
Also look at this
- https://stackoverflow.com/questions/40207171/why-shared-timed-mutex-is-defined-in-c14-but-shared-mutex-in-c17
- https://www.justsoftwaresolutions.co.uk/threading/new-concurrency-features-in-c++14.html