【C++编程】条件变量condition_variable
正文
std::condition_variable 条件变量
void wait( std::unique_lock<std::mutex>& lock ); #1
template< class Predicate >
void wait( std::unique_lock<std::mutex>& lock, Predicate stop_waiting ); #2
多线程轮流打印ABC
#include <iostream>
#include <thread>
#include <condition_variable>
#include <vector>
#include <algorithm>
#include <functional>
#include <thread>
#include <mutex>
std::mutex mtx;
std::condition_variable variable;
char g_ch = 0;
void print_fun(char ch) {
int cyle_cnt = 10;
char ch_ = ch - 'A';
for (int i = 0; i < cyle_cnt; i++) {
std::unique_lock<std::mutex> ulk(mtx);
variable.wait(ulk, [ch_] { return ch_ == g_ch; });
std::cout << (char)(ch_ + 'A') << std::endl;
g_ch = (ch_ + 1) % 3;
ulk.unlock();
variable.notify_all();
}
}
int main()
{
std::vector<std::thread> threads;
threads.push_back(std::thread(print_fun, 'A'));
threads.push_back(std::thread(print_fun, 'B'));
threads.push_back(std::thread(print_fun, 'C'));
std::for_each(threads.begin(), threads.end(), std::mem_fn(&std::thread::join));
std::cout << std::endl;
return 0;
}
例1 :
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <condition_variable>
std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;
void worker_thread()
{
std::unique_lock lk(m);
cv.wait(lk, [] { return ready; });
std::cout << "Worker thread is processing data\n";
data += " after processing";
processed = true;
std::cout << "Worker thread signals data processing completed\n";
lk.unlock();
cv.notify_one();
}
int main()
{
std::thread worker(worker_thread);
data = "Example data";
{
std::lock_guard lk(m);
ready = true;
std::cout << "main() signals data ready for processing\n";
}
cv.notify_one();
{
std::unique_lock lk(m);
cv.wait(lk, [] { return processed; });
}
std::cout << "Back in main(), data = " << data << '\n';
worker.join();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具