這是經典的同步互斥問題,
遵循原則:
1、條件變量需要鎖的保護;
2、鎖需要條件變量成立后,后重新上鎖;
參考代碼:
//notify_one()(隨機喚醒一個等待的線程) //notify_all()(喚醒所有等待的線程) //Create By@herongwei 2019/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; }