这是经典的同步互斥问题,
遵循原则:
1、条件变量需要锁的保护;2、锁需要条件变量成立后,后重新上锁;
参考代码:
//notify_one()(随机唤醒一个等待的线程)//notify_all()(唤醒所有等待的线程)//Create By@herongwei /09/10#include <bits/stdc++.h>#include <mutex>#include <thread>#include <condition_variable>using namespace std;std::mutex data_mutex;//互斥锁std::condition_variable data_var;//条件变量bool flag = true;void printfA() {int i = 1;while(i <= 100) {//休息1秒//std::this_thread::sleep_for(std::chrono::seconds(1));std::unique_lock<std::mutex> lck(data_mutex);data_var.wait(lck,[]{return flag;});//等待flag=true才打印奇数std::cout<<"A " << i <<endl;i += 2;flag = false;data_var.notify_one();}}void printfB() {int i = 2;while(i <= 100) {std::unique_lock<std::mutex> lck(data_mutex);data_var.wait(lck,[]{return !flag;});//等待flag=false才打印偶数std::cout<<"B " << i <<endl;i += 2;flag = true;data_var.notify_one();}}int main() {// freopen("in.txt","r",stdin);std::thread tA(printfA);std::thread tB(printfB);tA.join();tB.join();return 0;}
C++ 11,VS 使用了unique_lock,条件变量 条件变量的wait(), notify_one() wait()中使用了lambda表达式 代码 #include <iostream> #include <vector> #include <thread> #include <list> #include <mutex>思路2:
using namespace std;
bool flag = true;
{ public:class A
{ while (true) { std::unique_lock<std::mutex> lock1(print_mutex); data_var.wait(lock1, [] {return flag; }); cout << "thread: " << std::this_thread::get_id() << " print: " << "A" << endl;void print1()
data_var.notify_one(); } }flag = false;
{ while (true) { std::this_thread::sleep_for(std::chrono::seconds(1));void print2()
std::unique_lock<std::mutex> lock2(print_mutex);
cout << "thread: " << std::this_thread::get_id() << " print: " << "B" << endl;data_var.wait(lock2, [] {return !flag; });
data_var.notify_one(); } }flag = true;
private:
std::condition_variable data_var; };std::mutex print_mutex;
{ A myobj_a;int main()
std::thread print2(&A::print2, &myobj_a);std::thread print1(&A::print1, &myobj_a);
print2.join();print1.join();
}return 0;