forked from MouCoder/cpp_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlock&thread
More file actions
45 lines (42 loc) · 741 Bytes
/
lock&thread
File metadata and controls
45 lines (42 loc) · 741 Bytes
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
#include <iostream>
#include <mutex>
#include <thread>
#include <condition_variable>
using namespace std;
int main()
{
//两个线程轮流打印,顺序打印1-100
int a = 1;
int b = 2;
bool flag = true;
//一个互斥锁
mutex mtx;
//一个条件变量
condition_variable cd;
//创建两个线程A和B
thread t1([&]{
while(a <= 100)
{
unique_lock<std::mutex> lck(mtx);
cd.wait(lck, [flag]{return flag; });
cout << a << " ";
a += 2;
flag = false;
cd.notify_one();
}
});
thread t2([&]{
while (b <= 100)
{
unique_lock<std::mutex> lck(mtx);
cd.wait(lck, [flag]{return !flag; });
cout << b << " ";
b += 2;
flag = true;
cd.notify_one();
}
});
t1.join();
t2.join();
return 0;
}