条件变量可以履行发送者或接收者的角色。
作为发送者,它可以通知一个或多个接收者。
条件变量允许我们通过通知进而实现线程同步。
因此,您可以实现发送方/接收方或生产者/消费者之类的工作流。
#include <iostream>
#include <chrono>
#include <thread>
#include <iostream>
#include <condition_variable>
#include <mutex>
#include <thread>
std::mutex mutex_;
std::condition_variable condVar;
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);
doTheWork();
std::cout << "Work done." << std::endl;
}
void setDataReady() {
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Sender: Data is ready." << std::endl;
condVar.notify_one();
}
int main() {
std::thread t1(waitingForWork);
std::thread t2(setDataReady);
t1.join();
t2.join();
}