-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.cpp
More file actions
49 lines (43 loc) · 862 Bytes
/
ThreadPool.cpp
File metadata and controls
49 lines (43 loc) · 862 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
48
49
#include "ThreadPool.h"
void ThreadPool::threadWaitLoop()
{
while (!m_stop)
{
std::unique_lock<std::mutex> lock(m_mutexQueue);
m_condition.wait(lock, [&] {return !m_queue.empty() || m_stop;});
if (!m_queue.empty() && !m_stop)
{
auto task = m_queue.front();
m_queue.pop();
lock.unlock();
task();
}
else lock.unlock();
}
}
ThreadPool::ThreadPool()
{
if (!m_maxThreads)
m_maxThreads = 2;
for (int i = 0; i < m_maxThreads; i++)
{
m_pool.push_back(std::thread(&ThreadPool::threadWaitLoop, this));
}
}
void ThreadPool::addTask(std::function<void()> newTask)
{
std::unique_lock<std::mutex> lock(m_mutexQueue);
m_queue.push(newTask);
lock.unlock();
m_condition.notify_one();
}
void ThreadPool::stop()
{
m_stop = true;
m_condition.notify_all();
for (std::thread& thread : m_pool)
{
thread.join();
}
m_pool.clear();
}