Sobes.tech
Junior — Middle

What is the main role of std::condition_variable in multithreaded programming?

sobes.tech AI

Answer from AI

std::condition_variable is used for synchronization between threads in C++. It allows one or more threads to wait for a certain condition and suspend their execution until another event notifies them that this condition has been met.

Main roles:

  • Enables threads to wait efficiently for a change in state without busy-waiting.
  • Used together with std::mutex for safe access to shared data.

Example usage:

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void worker() {
    std::unique_lock<std::mutex> lock(mtx);
    cv.wait(lock, []{ return ready; }); // wait until ready becomes true
    // perform work
}

void signal() {
    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;
    }
    cv.notify_one(); // notify one waiting thread
}