forked from progschj/ThreadPool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ThreadPool.hpp
76 lines (62 loc) · 2.24 KB
/
ThreadPool.hpp
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
//
// Purpose: Simple thread pool
//
// Based on https://github.com/progschj/ThreadPool changes provided as https://github.com/calthron/ThreadPool
#pragma once
#include <condition_variable>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <queue>
#include <stdexcept>
#include <thread>
#include <vector>
class ThreadPool final
{
public:
// Launches specified number of worker threads
ThreadPool (size_t threads = 1);
~ThreadPool ();
// Not copyable
ThreadPool (const ThreadPool &) = delete;
ThreadPool& operator= (const ThreadPool &) = delete;
// Not moveable
ThreadPool (ThreadPool &&) = delete;
ThreadPool& operator= (const ThreadPool &&) = delete;
// Enqueue task and return std::future<>
template<typename Callable, typename... Args>
auto enqueue (Callable&& callable, Args&&... args)
-> std::future<typename std::result_of<Callable (Args...)>::type>;
private:
// Keep track of threads, so they can be joined
std::vector<std::thread> workers;
// Task queue
std::queue<std::function<void ()>> tasks;
// Synchronization
using lock_t = std::unique_lock<std::mutex>;
std::mutex queue_mutex;
std::condition_variable condition;
bool stop = false;
};
// Add a new work item to the pool, return std::future of return type
template<typename Callable, typename... Args>
auto ThreadPool::enqueue (Callable&& callable, Args&&... args)
-> std::future<typename std::result_of<Callable (Args...)>::type>
{
using return_t = typename std::result_of<Callable (Args...)>::type;
using task_t = std::packaged_task<return_t ()>;
auto task = std::make_shared<task_t> (std::bind (std::forward<Callable> (callable), std::forward<Args> (args)...));
std::future<return_t> result = task->get_future();
{ // Critical section
lock_t lock (queue_mutex);
// Don't allow an enqueue after stopping
if (stop)
throw std::runtime_error ("enqueue on stopped ThreadPool");
// Push work back on the queue
tasks.emplace ([task](){ (*task)(); });
} // End critical section
// Notify a thread that there is new work to perform
condition.notify_one ();
return result;
}