libstp
Robotics library for Botball
Loading...
Searching...
No Matches
thread_pool.hpp
Go to the documentation of this file.
1#pragma once
2
4
5#include <condition_variable>
6#include <cstddef>
7#include <functional>
8#include <future>
9#include <memory>
10#include <mutex>
11#include <queue>
12#include <tuple>
13#include <type_traits>
14#include <utility>
15#include <vector>
16
17namespace libstp::threading
18{
30 {
31 public:
32 explicit ThreadPool(std::size_t worker_count = 0);
34
35 ThreadPool(const ThreadPool&) = delete;
36 ThreadPool& operator=(const ThreadPool&) = delete;
37
40 template <typename F, typename... Args>
41 auto submit(F&& fn, Args&&... args)
42 -> std::future<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>
43 {
44 using R = std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>;
45 auto task = std::make_shared<std::packaged_task<R()>>(
46 [fn = std::forward<F>(fn),
47 tup = std::make_tuple(std::forward<Args>(args)...)]() mutable
48 {
49 return std::apply(std::move(fn), std::move(tup));
50 });
51 auto fut = task->get_future();
52 enqueue([task]() { (*task)(); });
53 return fut;
54 }
55
57 void wait_idle();
58
60 void shutdown();
61
62 [[nodiscard]] std::size_t worker_count() const noexcept { return workers_.size(); }
63
64 private:
65 void enqueue(std::function<void()> job);
66 void worker_loop(stop_token stop);
67
68 mutable std::mutex mu_;
69 std::condition_variable_any work_cv_;
70 std::condition_variable_any idle_cv_;
71 std::queue<std::function<void()>> queue_;
72 std::size_t in_flight_ = 0;
73 bool stopping_ = false;
74 std::vector<jthread> workers_;
75 };
76}
ThreadPool & operator=(const ThreadPool &)=delete
void shutdown()
Stop accepting new tasks and join all workers. Idempotent.
std::size_t worker_count() const noexcept
void wait_idle()
Block until the queue is empty and no tasks are in flight.
ThreadPool(std::size_t worker_count=0)
auto submit(F &&fn, Args &&... args) -> std::future< std::invoke_result_t< std::decay_t< F >, std::decay_t< Args >... > >
ThreadPool(const ThreadPool &)=delete
compat::stop_token stop_token