Condition Variables in C++ Multithreading
Last Updated :
01 May, 2024
In C++, the condition variable is a synchronization primitive that is used to notify the other threads in a multithreading environment that the shared resource is free to access. It is defined as the std::condition_variable class inside the <condition_variable> header file.
Prerequisite: C++ Multithreading, Mutex in C++.
Need for Condition Variable in C++
Condition variable is especially needed in cases where one thread has to wait for another thread execution to continue the work. For example, the producer-consumer relationship, sender-receiver relationship, etc.
In these cases, the condition variable makes the thread wait till it is notified by the other thread. It is used with mutex locks to block access to the shared resource when one thread is working on it.
Syntax of std::condition_variable
The syntax to declare a condition variable is simple:
std::condition_variable variable_name;
After that, we use the associated method for different operations.
Condition Variable Methods
The std::condition_variable methods contain some member methods to provide the basic functionalities. Some of these are:
S. No. | Function | Description |
---|
1
| wait() | This function tells the current thread to wait till the condition variable is notified. |
---|
2
| wait_for() | This function tells the current thread to wait for some specific time duration. If the condition variable is notified earlier than the time duration, the thread awakes. The time is specified as relative time. |
---|
3
| wait_until() | This function is similar to the wait_for() but here, the time duration is defined as the absolute time. |
---|
4
| notify_one() | This function notifies one of the waiting threads that the shared resource is free to access. The thread selection is random. |
---|
5
| notify_all() | This function notifies all of the threads. |
---|
Example: Program to Illustrate the Use of Condition Variable
C++
// C++ Program to illustrate the use of Condition Variables
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
// mutex to block threads
mutex mtx;
condition_variable cv;
// function to avoid spurios wakeup
bool data_ready = false;
// producer function working as sender
void producer()
{
// Simulate data production
this_thread::sleep_for(chrono::seconds(2));
// lock release
lock_guard<mutex> lock(mtx);
// variable to avoid spurious wakeup
data_ready = true;
// logging notification to console
cout << "Data Produced!" << endl;
// notify consumer when done
cv.notify_one();
}
// consumer that will consume what producer has produced
// working as reciever
void consumer()
{
// locking
unique_lock<mutex> lock(mtx);
// waiting
cv.wait(lock, [] { return data_ready; });
cout << "Data consumed!" << endl;
}
// drive code
int main()
{
thread consumer_thread(consumer);
thread producer_thread(producer);
consumer_thread.join();
producer_thread.join();
return 0;
}
Output
Data Produced!
Data consumed!
In this program, the consumer thread uses the condition variable cv to wait until data_ready is set to true while the producer thread sleeps for two seconds to mimic data generation.
Errors Associated with C++ Condition Variable
The condition variable is prone to the following errors:
- Spurious Wakeup: Spurious wakeup refers to the condition when the consumer/receiver thread finishes its work before it is notified by the producer/sender. In the above example, we have used the variable data_ready precisely to cope with this error.
- Lost Wakeup: Lost wakeup refers to the condition when the sender sends the notification but there is no receiver in the wait for the notification yet.
Advantages of Condition Variable
The following are the major advantages of using condition variables in our C++ program:
- The condition variable provide a way to signal the thread of a particular condition.
- The sleeping thread in condition variable is different from the waiting threads consuming less resources.
Conclusion
In conclusion, condition variables are an effective tool for assuring safe access to shared data, lowering contention, and establishing effective thread synchronisation in multi-threaded C++ programmes. They are commonly used with the mutex to provide an efficient synchronization technique.
Similar Reads
Multithreading in C++
Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith
6 min read
Handling Race Condition in Distributed System
In distributed systems, managing race conditions where multiple processes compete for resources demands careful coordination to ensure data consistency and reliability. Addressing race conditions involves synchronizing access to shared resources, using techniques like locks or atomic operations. By
11 min read
Packaged Task | Advanced C++ (Multithreading & Multiprocessing)
The  std::packaged_task class wraps any Callable objects (function, lambda expression, bind expression, or another function object) so that they can be invoked asynchronously. A packaged_task won't start on its own, you have to invoke it, As its return value is stored in a shared state that can be c
3 min read
Decision Making in C++
Decision-making is the process to make a decision about which part of the code should be executed or not based on some condition. Decision-making in C++ involves the usage of conditional statements (also called decision control statements) to execute specific blocks of code primarily based on given
8 min read
Multithreading or Multiprocessing with Python and Selenium
Multithreading and multiprocessing are two popular approaches for improving the performance of a program by allowing it to run tasks in parallel. These approaches can be particularly useful when working with Python and Selenium, as they allow you to perform multiple actions simultaneously, such as a
11 min read
Thread Synchronization in C++
In C++ multithreading, synchronization between multiple threads is necessary for the smooth, predictable, and reliable execution of the program. It allows the multiple threads to work together in conjunction by having a proper way of communication between them. If we do not synchronize the threads w
7 min read
continue Statement in C++
C++ continue statement is a loop control statement that forces the program control to execute the next iteration of the loop. As a result, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin. Syntax: continue; Example: Consider the
5 min read
Thread hardware_concurrency() function in C++
Thread::hardware_concurrency is an in-built function in C++ std::thread. It is an observer function which means it observes a state and then returns the corresponding output. This function returns the number of concurrent threads supported by the available hardware implementation. This value might n
1 min read
How to Thread Lock Work in C#?
C# makes the concurrent execution of a code possible with the help of threads. The namespace System. Threading which is pre-built in C# supports the use of threads. Typically we create threads for the concurrent execution of a program. But in certain cases we may not want our program to be run concu
4 min read
Sleep Function in C++
C++ provides the functionality of delay or inactive state of the program with the help of the operating system for a specific period of time. Other CPU operations will function adequately but the sleep() function in C++ will sleep the present executable for the specified time by the thread. The slee
4 min read