-
Notifications
You must be signed in to change notification settings - Fork 1
/
item39_void_future_one_shot_communication.cpp
75 lines (62 loc) · 1.38 KB
/
item39_void_future_one_shot_communication.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include "type_name.hpp"
#include <thread>
#include <condition_variable>
#include "unistd.h"
#include <vector>
#include <future>
using namespace std;
/* Interrupt message */
std::condition_variable cv;
std::mutex m;
/* use conditional variable to notify*/
bool flag(false);
void teller(){
std::lock_guard<std::mutex> g(m);
flag =true;
cv.notify_one();
}
void reactor(){
std::unique_lock<std::mutex> lk(m);
cv.wait(lk,[] { cout << "flag :" << flag << endl; return flag;});
}
/* Use std::future and std::promise */
std::promise<void> p;
void reactor1();
void teller1(){
cout << "in teller1 \n";
/* p.get_future.wait() suspend t until future is set. */
std::thread t([]{p.get_future().wait();reactor1();});
p.set_value();
t.join();
}
void reactor1(){
cout << "in reactor \n";
//throw "abc";
//p.get_future.wait();
}
/* ThreadRAII class */
//class ThreadRAII
/* Need process exception before promise.set_value */
void detect1(){
auto sf = p.get_future().share();
std::vector<std::thread> vt;
for(int i = 0; i < 3; ++i){
vt.emplace_back([sf]{sf.wait(); reactor1();});
}
// try{
// }
p.set_value();
for(auto& t: vt){
t.join();
}
}
int main(){
std::thread t1(teller);
usleep(10000);
//std::thread t2(reactor);
reactor();
t1.join();
teller1();
return 0;
}