Search⌘ K
AI Features

- Example

Understand how to coordinate multiple threads in a C++ program by using condition variables to wait and notify threads. Learn the roles of std::unique_lock and std::lock_guard, how to check predicates safely, and manage complex waiting workflows to ensure proper synchronization in concurrent programming.

We'll cover the following...

Example

C++
// conditionVariable.cpp
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <thread>
std::mutex mutex_;
std::condition_variable condVar;
bool dataReady{false};
void doTheWork(){
std::cout << "Processing shared data." << std::endl;
}
void waitingForWork(){
std::cout << "Worker: Waiting for work." << std::endl;
std::unique_lock<std::mutex> lck(mutex_);
condVar.wait(lck, []{ return dataReady; });
doTheWork();
std::cout << "Work done." << std::endl;
}
void setDataReady(){
{
std::lock_guard<std::mutex> lck(mutex_);
dataReady = true;
}
std::cout << "Sender: Data is ready." << std::endl;
condVar.notify_one();
}
int main(){
std::cout << std::endl;
std::thread t1(waitingForWork);
std::thread t2(setDataReady);
t1.join();
t2.join();
std::cout << std::endl;
}

Explanation

  • The program has two child threads: t1 and t2.

  • They get their work packages, waitingForWork and setDataReady, in lines 38 and 39. Using the condition variable condVar, setDataReady notifies that its work is done with the preparation of the ...