Junior — Middle
Can you list the existing types of mutual exclusions (mutex)?
sobes.tech AI
Answer from AI
There are different types of mutual exclusions (mutex) in C/C++, which differ in implementation and capabilities:
- Simple (regular) mutex — a basic locking mechanism that provides exclusive access to a resource.
- Recursive mutex — allows the same thread to lock the mutex multiple times without deadlock.
- Timed mutex — a mutex with the ability to attempt locking with a timeout.
- Error-checking mutex — a mutex that checks for errors, for example, re-locking by the same thread causes an error.
The C++11 standard library includes the following types:
std::mutexstd::recursive_mutexstd::timed_mutexstd::recursive_timed_mutex
Example of using std::recursive_mutex:
#include <mutex>
std::recursive_mutex mtx;
void recursive_function(int count) {
mtx.lock();
if (count > 0) {
recursive_function(count - 1);
}
mtx.unlock();
}
The choice of mutex type depends on the task and locking requirements.