Can you list the types of mutexes and their features?
sobes.tech AI
Answer from AI
In C/C++, there are different types of mutexes that vary in behavior and usage:
-
std::mutex — the basic mutex that provides mutual exclusion. If a thread tries to acquire a mutex that is already locked, it blocks until the mutex is released.
-
std::timed_mutex — an extension of std::mutex that allows attempting to acquire the mutex with a timeout to avoid infinite waiting.
-
std::recursive_mutex — allows the same thread to lock the mutex multiple times without deadlock. It is important to unlock the mutex the same number of times it was locked.
-
std::shared_mutex (C++17) — supports shared (read) and exclusive (write) access. Multiple threads can acquire shared locks simultaneously for reading, but only one thread can acquire a unique lock for writing.
-
std::recursive_timed_mutex — combines recursion and timeouts.
Example of using std::mutex:
#include <mutex>
std::mutex mtx;
void critical_section() {
mtx.lock();
// critical section
mtx.unlock();
}
For safer code, it is recommended to use std::lock_guard or std::unique_lock, which automatically release the mutex.