C ++ multi-threaded base study notes (six)

condition_variable, wait, notifiy_one, notify_all of use

condition_variable: Variable Conditions

wait: waiting to be awakened

notify_one: random wake up a thread

notify_all: wake up all the threads

The following code is a three threads in turn Digital Printing

 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 ();    // wake up all the threads are locked 
31 is              }
 32          }
 33 is      }
 34 is      void print2 () {
 35          the while (COUNT < . 8 ) {
 36              unique_lock is <the mutex> myunique (mymutex);
 37 [              IF (! In Flag = 2 ) {
 38 is                  my_cond.wait (myunique);
 39              }
 40              the 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 }

Guess you like

Origin www.cnblogs.com/main404/p/11258320.html