Junior — Middle
What is the difference between a mutex lock and a condition variable in thread synchronization?
sobes.tech AI
Answer from AI
Mutex (mutual exclusion) is a synchronization primitive that provides exclusive access to a resource: at any given moment, only one thread can own the mutex and work with the protected data.
Condition Variable is a mechanism that allows a thread to wait for a certain condition to occur and, in the process, releases the mutex so that other threads can change the state, after which the waiting thread will be awakened.
Main differences:
- Mutex blocks access to a resource, preventing concurrent execution of a critical section.
- Condition Variable is used to organize waiting and notification between threads, allowing one thread to wait for an event and another to signal its occurrence.
Example of usage:
std::mutex mtx;
std::condition_variable cv;
bool ready = false;
// Consumer thread
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, []{ return ready; }); // waits until ready == true
// continues work after waking up
// Producer thread
{
std::lock_guard<std::mutex> guard(mtx);
ready = true;
}
cv.notify_one(); // signals the consumer
Thus, the mutex controls access, and the condition variable coordinates thread interaction through waiting and notification.