-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathC++11thread.cpp
More file actions
60 lines (55 loc) · 1.32 KB
/
C++11thread.cpp
File metadata and controls
60 lines (55 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>
std::mutex data_mutex;
std::condition_variable data_var;
int flag = 1;
void printA()
{
int n = 5;
while(-- n)
{
// std::this_thread::sleep_for(std::chrono::seconds(1));
std::unique_lock<std::mutex> lck(data_mutex) ;
data_var.wait(lck,[]{return flag == 1;});
std::cout<<"thread: "<< std::this_thread::get_id() << " printf: " << "A" <<std::endl;
flag = 2;
// lck.unlock();
data_var.notify_all();
}
}
void printB()
{
int n = 5;
while(-- n)
{
std::unique_lock<std::mutex> lck(data_mutex) ;
data_var.wait(lck,[]{return flag == 2;});
std::cout<<"thread: "<< std::this_thread::get_id() << " printf: " << "B" <<std::endl;
flag = 3;
data_var.notify_all();
}
}
void printC()
{
int n = 5;
while(-- n)
{
std::unique_lock<std::mutex> lck(data_mutex);
data_var.wait(lck,[]{return flag == 3;});
std::cout <<"thread: " << std::this_thread::get_id() << " printf: " << "C" << std::endl;
flag = 1;
data_var.notify_all();
}
}
int main()
{
std::thread tA(printA);
std::thread tB(printB);
std::thread tC(printC);
tA.join();
tB.join();
tC.join();
return 0;
}