-
Notifications
You must be signed in to change notification settings - Fork 0
/
threads.cpp
59 lines (54 loc) · 1.31 KB
/
threads.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
#include "threads.hpp"
paz::LockedCv::LockedCv() : _mx(std::make_shared<std::mutex>()), _cv(std::
make_shared<std::condition_variable>()), _done(std::make_shared<bool>(
false)) {}
void paz::LockedCv::release()
{
std::lock_guard lk(*_mx);
*_done = true;
_cv->notify_all();
}
void paz::LockedCv::wait() const
{
std::unique_lock lk(*_mx);
_cv->wait(lk, [this](){ return *_done; });
}
paz::Threadpool::Threadpool() : _done(false)
{
const unsigned int numThreads = std::max(1u, std::thread::
hardware_concurrency());
_threads.reserve(numThreads);
for(std::size_t i = 0; i < numThreads; ++i)
{
_threads.emplace_back([this]()
{
while(true)
{
std::unique_lock lk(_mx);
_cv.wait(lk, [this](){ return _done || !_tasks.empty(); });
if(_done)
{
return;
}
auto task = _tasks.front();
_tasks.pop();
lk.unlock();
task.first();
task.second.release();
}
}
);
}
}
paz::Threadpool::~Threadpool()
{
{
std::lock_guard lk(_mx);
_done = true;
_cv.notify_all();
}
for(auto& n : _threads)
{
n.join();
}
}