概述
条件变量的使用,其实是一种多线程通知模式,当线程一使用完数据后,通过条件变量通知其他线程,C++11后开始支持。
说明
条件变量必须配合mutex使用,确保并发访问的排他性
std::unique_lock<std::mutex> lock(m);
线程让自我挂起,释放锁, 等待条件匹配
若next == index为false则线程挂起,释放锁,直到被唤醒;唤醒后再判断next == index,若为false则继续挂起,直到被唤醒同时条件为true。
cv.wait(lock, [=]{return next == index; });...
发送通知以唤醒等待队列中所有线程
cv.notify_all();
主线程等待线程结束
t.join
其他条件变量函数
notify_one 通知一个等待的线程
notify_all 通知所有等待的线程
wait 阻塞当前线程,直到条件变量被唤醒
wait_for 阻塞当前线程,直到条件变量被唤醒,或到指定时限时长后
wait_until 阻塞当前线程,直到条件变量被唤醒,或直到抵达指定时间点
native_handle 返回原生句柄
测试代码
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>std::mutex m;
std::condition_variable cv;
std::vector<int> result;
int next = 0;void worker(int index) {for (int i = 0; i < 10; i++) {std::unique_lock<std::mutex> lock(m);cv.wait(lock, [=]{return next == index; });std::cout << "worker " << index << "\n";result.push_back(index);next = next + 1;if (next > 2) { next = 1; };cv.notify_all();}
}int main() {std::thread worker1(worker, 1);std::thread worker2(worker, 2);{std::lock_guard<std::mutex> l(m);next = 1;}std::cout << "Start\n";cv.notify_all();worker1.join();worker2.join();for (int e : result) {std::cout << e << ' ';}std::cout << std::endl;
}
运行结果
我公司承接各类技术服务,主要聚焦于:stm32、单片机、嵌入式、QT应用开发、Web+Python+Django应用开发。欢迎合作。