condition_variable、wait、notifiy_one、notify_all的使用方式
condition_variable:条件变量
wait:等待被唤醒
notify_one:随机唤醒一个线程
notify_all:唤醒所有线程
下列代码是三个线程轮流打印数字
1 #include <iostream> 2 #include <thread> 3 #include <mutex> 4 using namespace std; 5 6 class print 7 { 8 private: 9 mutex mymutex; //互斥锁 10 condition_variable my_cond; //条件变量 11 int num; 12 int flag; 13 int count; 14 public: 15 print() { 16 num = 1; 17 flag = 1; 18 count = 0; 19 } 20 void print1() { 21 while (count < 8) { 22 unique_lock<mutex> myunique(mymutex); 23 if (flag != 1) { 24 my_cond.wait(myunique); //等待被notify_one或者notify_all唤醒 25 } 26 else { 27 flag = 2; 28 cout << "thread_1:" << num++ << endl; 29 count++; 30 my_cond.notify_all(); //唤醒所有被锁的线程 31 } 32 } 33 } 34 void print2() { 35 while (count < 8) { 36 unique_lock<mutex> myunique(mymutex); 37 if (flag != 2) { 38 my_cond.wait(myunique); 39 } 40 else { 41 cout << "thread_2:" << num++ << endl; 42 flag = 3; 43 count++; 44 my_cond.notify_all(); 45 } 46 } 47 } 48 void print3() { 49 while (count < 8) { 50 unique_lock<mutex> myunique(mymutex); 51 if (flag != 3) { 52 my_cond.wait(myunique); 53 } 54 else { 55 flag = 1; 56 cout << "thread_3:" << num++ << endl; 57 count++; 58 my_cond.notify_all(); 59 } 60 } 61 } 62 }; 63 int main() 64 { 65 print p; 66 thread thread_1(&print::print1, &p); 67 thread thread_2(&print::print2, &p); 68 thread thread_3(&print::print3, &p); 69 thread_1.join(); 70 thread_2.join(); 71 thread_3.join(); 72 system("pause"); 73 return 0; 74 }