forked from progschj/ThreadPool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadPool.cpp
62 lines (52 loc) · 1.43 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
//
// Purpose: Simple thread pool
//
// Based on https://github.com/progschj/ThreadPool changes provided as https://github.com/calthron/ThreadPool
#include "ThreadPool.hpp"
ThreadPool::ThreadPool (size_t threads)
{
workers.reserve (threads);
for (size_t count = 0; count < threads; ++count)
{
// Worker execution loop
workers.emplace_back ([this]()
{
for (;;)
{
// Task to execute
std::function<void ()> task;
// Wait for additional work signal
{ // CRITICAL SECTION
// Wait to be notified of work
lock_t lock (queue_mutex);
condition.wait (lock, [this]()
{
return stop || !tasks.empty ();
});
// If stopping and no work remains, exit the work loop
if (stop && tasks.empty ())
break;
// Dequeue the next task
task.swap (tasks.front ());
tasks.pop ();
} // END CRITICAL SECTION
// Execute
task ();
}
});
}
}
// Destructor joins all worker threads
ThreadPool::~ThreadPool ()
{
{ // Critical section
lock_t lock (queue_mutex);
stop = true;
} // End critical section
condition.notify_all ();
// Wait for threads to complete work
for (std::thread &worker : workers)
{
worker.join();
}
}