C++ Library - <condition_variable>



The <condition_variable> in C++ is a synchronization primitive that allows threads to wait for certain conditions to be met before proceeding. It is useful in multi-threading applications, where one or more threads need to coordinate their actions based on shared data. By using condition variables, we can manage concurrent tasks, ensuring that threads either wait or proceed depending on specific conditions.

It is used in conjunction with std::mutex and is generally used with std::unique_lock. The unique_lock is passed to the condition_variable to release the lock when the thread is waiting, allowing the other threads to modify the shared data.

Including <condition_variable> Header

To include the <condition_variable> header in your C++ program, you can use the following syntax.

#include <condition_variable>

Functions of <condition_variable> Header

Below is list of all functions from <condition_variable> header.

Sr.No. Functions & Description
1 notify_one

It notifies one waiting thread.

2 notify_all

It notifies all waiting threads.

3 wait

It blocks the current thread until the condition variable is awakened.

4 wait_for

It blocks the current thread until the condition variable is awakened or after the specified timeout duration.

Thread Waiting

In the following example, we are going to show how a thread can wait for a condition to be true.

#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
std::mutex a;
std::condition_variable b;
bool ready = false;
void x() {
   std::unique_lock < std::mutex > lock(a);
   std::cout << "Waiting For Signal..." << std::endl;
   b.wait(lock, [] {
      return ready;
   });
   std::cout << "Signal Received" << std::endl;
}
int main() {
   std::thread y(x);
   std::this_thread::sleep_for(std::chrono::seconds(3));
   {
      std::lock_guard < std::mutex > lock(a);
      ready = true;
   }
   b.notify_one();
   y.join();
   return 0;
}

Output

Following is the output of the above code −

Waiting For Signal...
Signal Received
Advertisements