-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy paththreadpool.cpp
64 lines (59 loc) · 1.68 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
/* \file
\brief A demo threadpool implementation
*/
#include "threadpool.hpp"
ThreadPool::ThreadPool(size_t thread_count)
: task_count_(0u), stop_(false)
{
for (size_t i = 0; i < thread_count; i++)
{
// Each thread executes this lambda
workers_.emplace_back([this]()->void
{
while (true)
{
std::function<void()> task;
{ // acquire lock
std::unique_lock<std::mutex> lock(mutex_);
condition_.wait(lock, [this]()->bool
{
return !tasks_.empty() || stop_;
});
if (stop_ && tasks_.empty())
{
return;
}
task = std::move(tasks_.front());
tasks_.pop();
} // release lock
task();
task_count_--;
}
});
}
}
ThreadPool::~ThreadPool()
{
stop_ = true;
condition_.notify_all();
for (auto& w: workers_)
{
w.join();
}
}
void ThreadPool::schedule(const std::function<void()>& task)
{
{
std::unique_lock<std::mutex> lock(mutex_);
tasks_.push(task);
}
task_count_++;
condition_.notify_one();
}
void ThreadPool::waitAll() const
{
while (task_count_ != 0u)
{
std::this_thread::yield();
}
}