-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathc81_thread_pool.cpp
More file actions
116 lines (100 loc) · 2.4 KB
/
c81_thread_pool.cpp
File metadata and controls
116 lines (100 loc) · 2.4 KB
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
110
111
112
113
114
115
116
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <functional>
#include <future>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
/*!
* \brief A thread pool implementation using the concurrent queue from c79.cpp
*/
std::mutex cout_mutex; // mutex for cout
namespace concurrency
{
template<typename T>
class ConcurrentQueue
{
public:
ConcurrentQueue() = default;
~ConcurrentQueue() = default;
void push(T value)
{
std::unique_lock<std::mutex> lock{_m};
_data.push(value);
lock.unlock();
_cond.notify_one();
}
void pop(T& value)
{
std::unique_lock<std::mutex> lock{_m};
_cond.wait(lock, [this]() {
std::lock_guard<std::mutex> l{cout_mutex};
std::cout << "waiting\n";
return !_data.empty();
});
value = _data.front();
_data.pop();
}
private:
std::queue<T> _data;
std::mutex _m;
std::condition_variable _cond;
};
class ThreadPool
{
public:
ThreadPool()
{
for (size_t i = 0; i < std::thread::hardware_concurrency(); ++i)
// for (size_t i = 0; i < 2; ++i)
{
std::unique_lock<std::mutex> l{cout_mutex};
std::cout << "Creating thread\n";
l.unlock();
_threads.push_back(std::thread{[this]() {
while (true)
{
std::function<void()> task;
_tasks.pop(task);
task();
}
}});
}
}
~ThreadPool()
{
for (auto& t : _threads)
{
t.join();
}
}
void submit(std::function<void()> task)
{
_tasks.push(task);
}
private:
std::vector<std::thread> _threads;
ConcurrentQueue<std::function<void()>> _tasks;
};
}
int main()
{
std::cout << "Num of hardware threads: "
<< std::thread::hardware_concurrency << std::endl;
concurrency::ThreadPool pool;
for (size_t i = 0; i < 12; ++i)
{
pool.submit([]() {
std::unique_lock<std::mutex> l{cout_mutex};
std::cout << "thread #" << std::this_thread::get_id()
<< " executing" << std::endl;
l.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(200));
return;
});
}
return 0;
}