The term mutex stands for mutual exclusion. In order to prevent that concurrently running threads alter the same object in a non-orchestrated way that might lead to data corruption, we can use mutex objects. The STL provides different mutex classes with different specialties. They all have in common that they have a lock and an unlock method.
Whenever a thread is the first one to call lock() on a mutex that was not locked before, it owns the mutex. At this point, other threads will block on their lock calls, until the first thread calls unlock again. std::mutex can do exactly this.
There are many different mutex classes in the STL:
| Type name | Description |
| mutex |
Standard mutex with a lock and an unlock method. Provides an additional nonblocking try_lock method. |
| timed_mutex |
Same as mutex, but provides additional try_lock_for and try_lock_until methods that allow for timing out instead of blocking forever. |
| recursive_mutex |
Same as mutex, but if a thread locked an instance of it already, it can call lock multiple times on the same mutex object without blocking. It is released after the owning thread called unlock as often as it called lock. |
| recursive_timed_mutex |
Provides the features of both timed_mutex and recursive_mutex. |
| shared_mutex |
This mutex is special in that regard, that it can be locked in exclusive mode and in shared mode. In exclusive mode, it shows the same behavior as the standard mutex class. If a thread locks it in shared mode, it is possible for other threads to lock it in shared mode, too. It will then be unlocked as soon as the last shared mode lock owner releases it. While a lock is locked in shared mode, it is not possible to obtain exclusive ownership. This is very similar to the behavior of shared_ptr, only that it does not manage memory, but lock ownership. |
| shared_timed_mutex |
Combines the features of shared_mutex and timed_mutex for both exclusive and shared mode. |