-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOving2.cpp
109 lines (94 loc) · 2.54 KB
/
Oving2.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include <iostream>
#include <vector>
#include <thread>
#include <condition_variable>
#include <list>
#include <mutex>
#include <functional>
#include <chrono>
using namespace std;
using namespace chrono;
class Workers {
private:
int numOfThreads;
condition_variable cv;
vector<thread> threads;
list<function<void()>> tasks;
mutex tasks_mutex;
bool run = true;
bool waiting;
public:
Workers(int num) {
numOfThreads = num;
}
void start() {
for(int i = 0; i < numOfThreads; i++){
threads.emplace_back([this] {
while(run) {
function<void()> task;
{
unique_lock<mutex> lock(tasks_mutex);
while(waiting) {
cv.wait(lock);
}
waiting = true;
if(!tasks.empty()) {
task = *tasks.begin();
tasks.pop_front();
}
lock.unlock();
waiting = false;
cv.notify_one();
}
if(task) {
task();
}
}
});
}
cv.notify_one();
}
void post(function<void()> f) {
unique_lock<mutex> lock(tasks_mutex);
tasks.emplace_back(f);
lock.unlock();
waiting = false;
cv.notify_one();
}
void stop() {
run = false;
for(auto& t : threads){
t.join();
}
}
void post_timeout(const function<void()>& function, int t) {
this_thread::sleep_for(milliseconds (t));
unique_lock<mutex> lock(tasks_mutex);
tasks.emplace_back(function);
waiting = false;
cv.notify_one();
}
};
int main() {
Workers worker_threads(4);
Workers event_loop(1);
worker_threads.start();
event_loop.start();
worker_threads.post([] {
cout << "A" << endl;
});
worker_threads.post([] {
cout << "B" << endl;
});
event_loop.post([] {
cout << "C" << endl;
});
event_loop.post([] {
cout << "D" << endl;
});
worker_threads.post_timeout([] {
cout << "Timeout thread_id: " << this_thread::get_id() << endl;
}, 1000);
worker_threads.stop();
event_loop.stop();
}