-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadPool.cpp
68 lines (58 loc) · 1.27 KB
/
ThreadPool.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
#include <ppl.h>
#include <thread>
#include <vector>
#include <concurrent_queue.h>
struct Work
{
void run()
{
func();
}
std::function<void()> func;
};
struct ThreadPool
{
void init(int N)
{
stopped = false;
for (int i = 0; i < N; ++i)
{
workers.push_back(
std::thread([this] () {
while (!stopped || !wqueue.empty())
{
Work w;
if (wqueue.try_pop(w))
{
w.run();
}
}
}
)
);
}
}
void start(std::function<void()> func)
{
Work w;
w.func = func;
wqueue.push(w);
}
void stop()
{
stopped = true;
for (auto&& t: workers)
t.join();
}
concurrency::concurrent_queue<Work> wqueue;
std::vector<std::thread> workers;
std::atomic<bool> stopped;
};
int main()
{
ThreadPool pool;
pool.init(10);
for (int i = 0; i < 50; ++i)
pool.start([]() { std::cout <<std::this_thread::get_id()<<std::endl;});
pool.stop();
}