Syntax for Mutex in C++
The use of mutex can be divided into three steps:
1. Create a std::mutex Object
std::mutex mutex_object_name;
2. Lock the Thread
The lock() function of the std::mutex class locks the thread and allows only the current thread to run until it is unlocked. It prevents the shared resource from being accessed by multiple threads simultaneously.
mutex_object_name.lock()
3. Unlock the thread
The unlock() of the std::mutex function is used to release the lock after execution of the code piece containing the possibility of race condition occurrence. It resumes all the waiting threads.
mutex_object_name.unlock()
Mutex in C++
Mutex stands for Mutual Exclusion. In C++, std::mutex class is a synchronization primitive that is used to protect the shared data from being accessed by multiple threads simultaneously. The shared data can be in the form of variables, data structures, etc.
std::mutex class implements mutex in C++. It is defined inside <mutex> header file.
Contact Us