-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread_pool.h
86 lines (67 loc) · 2.13 KB
/
thread_pool.h
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
80
81
82
83
84
85
86
#ifndef THREAD_POOL_H
#define THREAD_POOL_H
#include <atomic>
#include <cstddef>
#include <functional>
#include <future>
#include <thread>
#include <type_traits>
#include <vector>
#include "util/async_result.h"
#include <ds/concurrent_block_queue.h>
#include <util/function_wrapper.h>
namespace util {
class ThreadPool {
using WaitableTask = FunctionWrapper;
using TaskQueue = ds::ConcurrentBlockQueue<WaitableTask>;
using WorkerGroup = std::vector<std::jthread>;
TaskQueue tasks;
WorkerGroup workers;
std::atomic_bool done{false}; // true = complete all remaining work & exit
void worker_method() {
while (!done) {
// wait_and_pop requires interruptible conditional variable
// to wake the threads up in case a join( ) request received
// when there are no tasks available
auto task = tasks.try_pop();
if (task)
(*task)();
// irrespective of availability of tasks,
// give a chance to other threads
std::this_thread::yield();
}
}
static size_t compute_concurrency() {
return std::thread::hardware_concurrency() + 1;
}
public:
ThreadPool(const size_t total_workers = compute_concurrency()) : done(false) {
try {
for (auto i = 0u; i < total_workers; ++i)
workers.emplace_back(
std::jthread(&util::ThreadPool::worker_method, this));
} catch (...) {
join();
throw;
}
}
ThreadPool(const ThreadPool&) = delete;
ThreadPool& operator=(const ThreadPool&) = delete;
ThreadPool(ThreadPool&&) = delete;
ThreadPool& operator=(ThreadPool&&) = delete;
~ThreadPool() { join(); }
void join() { done = true; }
inline size_t size() const { return workers.size(); }
template <typename Fn, typename... Args>
auto submit(Fn callable, Args&&... args) {
using return_t = std::invoke_result_t<Fn, Args...>;
std::packaged_task<return_t()> task(
std::bind(std::forward<Fn>(callable), std::forward<Args>(args)...));
// caller waits on this future
AsyncResult<return_t> result{task.get_future()};
tasks.push(std::move(task));
return result;
}
};
}; // namespace util
#endif // THREAD_POOL_H