-
Notifications
You must be signed in to change notification settings - Fork 2
/
condition_vari-4.1.cpp
44 lines (41 loc) · 1.05 KB
/
condition_vari-4.1.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
#include <iostream>
#include <mutex>
#include <queue>
#include <condition_variable>
#include <thread>
#include <unistd.h>//sleep
std::mutex mut;
std::queue<int> data_queue;
std::condition_variable data_cond;
void data_preparation_thread(){
int data = 0;
while(true){
data++;
std::lock_guard<std::mutex> lk(mut);
data_queue.push(data);
data_cond.notify_one();
std::cout << "after notify_one" << std::endl;
//std::this_thread::sleep_for(1000);
sleep(1);
}
}
void data_process_thread(){
while(true){
std::unique_lock<std::mutex> lk(mut);
std::cout << "before wait" << std::endl;
data_cond.wait(lk, []{return !data_queue.empty();});
std::cout << "after wait" << std::endl;
int data = data_queue.front();
std::cout << data << std::endl;
data_queue.pop();
lk.unlock();
//假设处理数据data的函数process要花费大量时间,所以提前解锁
//process(data);
}
}
int main(){
std::thread t1(data_preparation_thread);
std::thread t2(data_process_thread);
t1.join();
t2.join();
}