48 : context_(
context), task_count_(std::make_shared<size_t>(0))
56 [[nodiscard]] ThreadPoolContext &
context() {
return context_; }
66 template <
class Func,
class Alloc>
67 void post(Func function,
const Alloc &allocator)
const
69 auto new_task(std::allocate_shared<Task<Func>>(
70 typename std::allocator_traits<Alloc>::template rebind_alloc<char>(allocator), std::move(function),
72 context_.post(new_task, task_count_);
81 std::unique_lock<std::mutex> lock(context_.mutex_);
82 while (*task_count_ > 0)
83 if (!context_.execute_next(lock)) context_.condition_.wait(lock);
93 struct Task : ThreadPoolContext::Function
95 explicit Task(Func func,
const std::shared_ptr<size_t> &task_count) : function(std::move(func))
97 work_count_ = task_count;
98 execute_ = [](std::shared_ptr<ThreadPoolContext::Function> &p)
100 Func tmp(std::move(
static_cast<Task *
>(p.get())->function));
109 void on_work_started()
111 std::lock_guard lock(context_.mutex_);
112 context_.do_work_started(task_count_);
116 void on_work_finished()
118 std::lock_guard lock(context_.mutex_);
119 context_.do_work_finished(task_count_);
126 template <
class Func,
class Alloc>
128 [[maybe_unused]]
void dispatch(Func,
const Alloc &)
const
135 template <
class Func,
class Alloc>
137 [[maybe_unused]]
void defer(Func,
const Alloc &)
const
141 ThreadPoolContext &context_;
142 std::shared_ptr<size_t> task_count_;
Context for reusable thread pool class, a modified example from asio documentation.