forked from ArthurFirmino/gym-battlesnake
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy paththreadpool.cpp
62 lines (54 loc) · 1.56 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
#include "threadpool.h"
ThreadPool::ThreadPool()
: _workers(),
_taskQueue(),
_taskCount( 0u ),
_mutex(),
_condition(),
_stop( false ) {}
ThreadPool::ThreadPool( size_t threads ) : ThreadPool() {
initializeWithThreads( threads );
}
ThreadPool::~ThreadPool() {
_stop = true;
_condition.notify_all();
for ( std::thread& w: _workers ) {
w.join();
}
}
void ThreadPool::initializeWithThreads( size_t threads ) {
for ( size_t i = 0; i < threads; 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 !_taskQueue.empty() || _stop;
});
if ( _stop && _taskQueue.empty() ) {
return;
}
task = std::move( _taskQueue.front() );
_taskQueue.pop();
} // release lock
task();
_taskCount--;
}
});
}
}
void ThreadPool::schedule( const std::function<void()>& task ) {
{
std::unique_lock<std::mutex> lock( _mutex );
_taskQueue.push( task );
}
_taskCount++;
_condition.notify_one();
}
void ThreadPool::wait() const {
while( _taskCount.load() > 0 ) {
std::this_thread::yield();
}
}