-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.cpp
More file actions
47 lines (42 loc) · 1014 Bytes
/
ThreadPool.cpp
File metadata and controls
47 lines (42 loc) · 1014 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
37
38
39
40
41
42
43
44
45
46
47
#include "ThreadPool.h"
// if tasks is empty, the thread wait until it is informed
// lock, accquire tasks.size(), if tasks is not empty,
ThreadPool::ThreadPool(int n)
{
if (n < 0)
return;
// create max of worker Threads...
is_stop = false;
auto worker = [this]()
{
while (1)
{
std::unique_lock<std::mutex> lock(m_mtx);
m_cv.wait(lock, [this]()
{ return !m_tasks.empty() || is_stop; });
if (is_stop && m_tasks.empty())
{
return;
}
auto task{std::move(m_tasks.front())};
m_tasks.pop();
lock.unlock();
task();
}
};
for (int i = 0; i < n; i++)
{
m_workers.push_back(std::thread{worker});
}
}
ThreadPool::~ThreadPool()
{
std::unique_lock<std::mutex> lock(m_mtx);
is_stop = true;
lock.unlock();
m_cv.notify_all();
for (auto &t : m_workers)
{
t.join();
}
}