-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallel_scheduler.cpp
75 lines (57 loc) · 1.5 KB
/
parallel_scheduler.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 <thread>
#include <atomic>
#include "thread_synchronizer.h"
using namespace std;
int main( int argc, char* argv[] ) {
WaitNotifyMultipleWaiters wn_fan_out(3);
WaitNotifyMultipleNotifiers wn_fan_in(3);
mutex mt;
atomic_int cnt(0);
auto task1 = [&] {
while (true) {
wn_fan_out.wait(0);
if (wn_fan_out.isTerminating())
break;
mt.lock();
cout << "task 1 cnt:" << to_string(cnt.load()) << "\n" << flush;
mt.unlock();
wn_fan_in.notify();
}
};
auto task2 = [&] {
while (true) {
wn_fan_out.wait(1);
if (wn_fan_out.isTerminating())
break;
mt.lock();
cout << "task 2 cnt:" << to_string(cnt.load()) << "\n" << flush;
mt.unlock();
wn_fan_in.notify();
}
};
auto task3 = [&] {
while (true) {
wn_fan_out.wait(2);
if (wn_fan_out.isTerminating())
break;
mt.lock();
cout << "task 3 cnt:" << to_string(cnt.load()) << "\n" << flush;
mt.unlock();
wn_fan_in.notify();
}
};
thread th1( task1 );
thread th2( task2 );
thread th3( task3 );
for ( int i = 0; i < 10 ; i++ ) {
wn_fan_out.notify();
wn_fan_in.wait();
cnt++;
}
wn_fan_out.terminate();
th1.join();
th2.join();
th3.join();
return 0;
}