-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreadPool.hpp
More file actions
106 lines (87 loc) · 2.81 KB
/
ThreadPool.hpp
File metadata and controls
106 lines (87 loc) · 2.81 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#ifndef _LIBRARY_UTILITIES_THREADPOOL_HPP
#define _LIBRARY_UTILITIES_THREADPOOL_HPP
#include <atomic>
#include <cstddef>
#include <functional>
#include <future>
#include <thread>
#include <type_traits>
#include <vector>
#include <optional>
#include <utility>
#include "Utilities/AsyncResult.hpp"
#include "DataStructures/ConcurrentBlockQueue.hpp"
#include "Utilities/FunctionWrapper.hpp"
namespace Utilities
{
class ThreadPool
{
using WaitableTask = Utilities::FunctionWrapper;
using TaskQueue = DataStructures::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(&Utilities::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
Utilities::AsyncResult<return_t> result{task.get_future()};
tasks.push(std::move(task));
return result;
}
};
} // namespace Utilities
#endif // !_LIBRARY_UTILITIES_THREADPOOL_HPP