Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
Condition Variables in C++ Multithreading
Next article icon

Condition Variables in C++ Multithreading

Last Updated : 01 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.FunctionDescription

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:

  1. 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.
  2. 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:

  1. The condition variable provide a way to signal the thread of a particular condition.
  2. 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.


Next Article
Condition Variables in C++ Multithreading

A

ashish_rao_2373
Improve
Article Tags :
  • C++
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • CPP

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
    5 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
    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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences