13#include <condition_variable>
35 ThreadPool(std::size_t numThreads = std::thread::hardware_concurrency(), std::string_view
name =
"ThreadPool");
46 template<
typename F,
typename... Args>
49 if (_stopping.load(std::memory_order_acquire))
50 throw std::runtime_error(
"ThreadPool: submit on stopped pool");
52 using returnType = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;
54 auto task = std::make_shared<std::packaged_task<returnType()>>(
55 [f = std::forward<F>(fn), ...a = std::forward<Args>(args)]() {
56 return std::invoke(std::move(f), std::move(a)...);
60 std::future<returnType> future = task->get_future();
62 std::unique_lock lock(_mutex);
63 _queue.push({ [task]{ (*task)(); }, priority, _submitCounter++ });
76 std::
size_t workerCount() const noexcept {
return _workers.size(); };
77 std::string_view
name() const noexcept {
return _name; };
81 std::function<void()> fn;
85 bool operator<(
const Task& o)
const noexcept {
86 if (priority != o.priority)
87 return static_cast<uint8_t
>(priority) <
static_cast<uint8_t
>(o.priority);
88 return seqNum > o.seqNum;
92 void workerLoop(std::size_t workerId);
94 void shutdown() noexcept;
96 void setThreadName([[maybe_unused]] std::
size_t id) noexcept {
98 const std::string n = _name.size() > 10 ? _name.substr(0, 10) + std::to_string(
id) : _name + std::to_string(id);
99 pthread_setname_np(pthread_self(), n.c_str());
100#elif defined(__APPLE__)
101 const std::string n = _name + std::to_string(
id);
102 pthread_setname_np(n.c_str());
108 std::vector<std::thread> _workers;
109 std::priority_queue<Task> _queue;
111 mutable std::mutex _mutex;
112 std::condition_variable _cv;
113 std::condition_variable _drainCv;
115 std::atomic<bool> _stopping{
false };
116 std::atomic<bool> _paused{
false };
117 std::atomic<std::size_t> _activeTasks{ 0 };
118 std::uint64_t _submitCounter{ 0 };
Worker threads running tasks by priority, then in submission order.
Definition ThreadPool.hpp:24
auto submit(F &&fn, Priority priority=Priority::Normal, Args &&... args)
Queues fn(args...) and returns a std::future of its result.
Definition ThreadPool.hpp:47
Priority
Higher priorities run first.
Definition ThreadPool.hpp:27
bool isPaused() const noexcept
ThreadPool(ThreadPool &&)=delete
void pause() noexcept
Stops starting new tasks; running tasks finish.
void waitForAll()
Blocks until every queued task has run; do not call it while paused.
ThreadPool & operator=(ThreadPool &&)=delete
std::string_view name() const noexcept
Definition ThreadPool.hpp:77
ThreadPool & operator=(const ThreadPool &)=delete
ThreadPool(std::size_t numThreads=std::thread::hardware_concurrency(), std::string_view name="ThreadPool")
Starts numThreads workers, named after name in debuggers on Linux and macOS.
ThreadPool(const ThreadPool &)=delete
std::size_t workerCount() const noexcept
Definition ThreadPool.hpp:76
~ThreadPool()
Runs the queued tasks, then joins the workers.
Thread pool with task priorities.
Definition ThreadPool.hpp:16