cpp小实验,两个线程,一个线程负责将变量减一,另一个线程负责打印线程。

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
#include <thread>
#include <condition_variable>
#include <mutex>
#include <iostream>

int global_value = 10;
bool ready_to_reduce{false};
std::mutex mtx;
std::condition_variable cv_reduce;
std::condition_variable cv_print;

void producer() {
while(true) {
std::unique_lock<std::mutex> lock(mtx);
cv_reduce.wait(lock,[](){
return ready_to_reduce;
});
global_value--;
ready_to_reduce = !ready_to_reduce;
cv_print.notify_one();
if (global_value == 0) {
break;
}
}
}

void consumer() {
while(true) {
std::unique_lock<std::mutex> lock(mtx);
cv_print.wait(lock,[] () {
return !ready_to_reduce;
});
std::cout << global_value << std::endl;
if (global_value == 0) {
break;
}
ready_to_reduce = true;
cv_reduce.notify_one();
}
}

int main() {
auto t1 = std::thread(producer);
auto t2 = std::thread(consumer);
t1.join();
t2.join();
return 0;
}