-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththreadpool.cpp
80 lines (50 loc) · 1.24 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// project
#include "threadpool.h"
using namespace std;
ThreadPool::ThreadPool( const int _threads ) :
m_terminate(false),
m_stopped(false){
for(int i = 0; i < _threads; i++){
m_pool.emplace_back( thread(&ThreadPool::Worker, this, i) );
}
}
void ThreadPool::enqueue( Task *_task ){
{
std::unique_lock<std::mutex> lock(m_tasksMutex);
m_tasks.push( _task );
}
m_condition.notify_one();
}
void ThreadPool::Worker( int16_t /*_threadID*/ ){
Task * task;
while(true){
{
std::unique_lock<std::mutex> lock(m_tasksMutex);
// Wait until queue is not empty or termination signal is sent.
m_condition.wait( lock, [this]{ return !m_tasks.empty() || m_terminate; } );
if( m_terminate && m_tasks.empty() ){
return;
}
task = m_tasks.front();
m_tasks.pop();
}
task->process();
}
}
void ThreadPool::shutdown(){
{
std::unique_lock<std::mutex> lock(m_tasksMutex);
m_terminate = true;
}
m_condition.notify_all();
for( std::thread & thread : m_pool ){
thread.join();
}
m_pool.empty(); // TODO ?
m_stopped = true;
}
ThreadPool::~ThreadPool(){
if( ! m_stopped ){
shutdown();
}
}