-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathThreadPool.cxx
More file actions
36 lines (32 loc) · 863 Bytes
/
ThreadPool.cxx
File metadata and controls
36 lines (32 loc) · 863 Bytes
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
#include "ThreadPool.hpp"
// the constructor just launches some amount of workers
ThreadPool::ThreadPool(size_t threads)
: stop(false)
{
for(size_t i = 0; i<threads; ++i)
workers.emplace_back([this] {
for(;;) {
std::packaged_task<void()> task;
{
std::unique_lock<std::mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this]{ return this->stop || !this->tasks.empty(); });
if(this->stop && this->tasks.empty())
return;
task = std::move(this->tasks.front());
this->tasks.pop();
}
task();
}
});
}
// the destructor joins all threads
ThreadPool::~ThreadPool() {
{
std::unique_lock<std::mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for(std::thread& worker : workers)
worker.join();
}