RSTools 3.1.0
Versatile C++20 utility library
Loading...
Searching...
No Matches
ThreadPool.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <vector>
4#include <queue>
5#include <functional>
6#include <string>
7#include <stdexcept>
8#include <cstdint>
9
10#include <thread>
11#include <future>
12#include <mutex>
13#include <condition_variable>
14#include <atomic>
15
16namespace RST::Threads {
17
24 class ThreadPool {
25 public:
27 enum class Priority : uint8_t {
28 Low = 0,
29 Normal = 1,
30 High = 2,
31 };
32
35 ThreadPool(std::size_t numThreads = std::thread::hardware_concurrency(), std::string_view name = "ThreadPool");
38
39 ThreadPool(const ThreadPool&) = delete;
40 ThreadPool& operator=(const ThreadPool&) = delete;
43
46 template<typename F, typename... Args>
47 auto submit(F&& fn, Priority priority = Priority::Normal, Args&&... args)
48 {
49 if (_stopping.load(std::memory_order_acquire))
50 throw std::runtime_error("ThreadPool: submit on stopped pool");
51
52 using returnType = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;
53
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)...);
57 }
58 );
59
60 std::future<returnType> future = task->get_future();
61 {
62 std::unique_lock lock(_mutex);
63 _queue.push({ [task]{ (*task)(); }, priority, _submitCounter++ });
64 }
65 _cv.notify_one();
66 return future;
67 }
68
70 void pause() noexcept;
71 void resume() noexcept;
72 bool isPaused() const noexcept;
74 void waitForAll();
75
76 std::size_t workerCount() const noexcept { return _workers.size(); };
77 std::string_view name() const noexcept { return _name; };
78
79 private:
80 struct Task {
81 std::function<void()> fn;
82 Priority priority;
83 std::uint64_t seqNum;
84
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;
89 }
90 };
91
92 void workerLoop(std::size_t workerId);
93
94 void shutdown() noexcept;
95
96 void setThreadName([[maybe_unused]] std::size_t id) noexcept {
97#if defined(__linux__)
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());
103#endif
104 }
105
106 std::string _name;
107
108 std::vector<std::thread> _workers;
109 std::priority_queue<Task> _queue;
110
111 mutable std::mutex _mutex;
112 std::condition_variable _cv;
113 std::condition_variable _drainCv;
114
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 };
119 };
120
121}
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
void resume() noexcept
~ThreadPool()
Runs the queued tasks, then joins the workers.
Thread pool with task priorities.
Definition ThreadPool.hpp:16