Kaspersky Neuromorphic Platform  1.0.0
API Reference
Loading...
Searching...
No Matches
thread_pool_executor.h
Go to the documentation of this file.
1
21#pragma once
22
23#include <memory>
24#include <utility>
25
26#include "thread_pool_context.h"
27
28
33{
40{
41public:
47 explicit ThreadPoolExecutor(ThreadPoolContext &context)
48 : context_(context), task_count_(std::make_shared<size_t>(0))
49 {
50 }
51
56 [[nodiscard]] ThreadPoolContext &context() { return context_; }
57
66 template <class Func, class Alloc>
67 void post(Func function, const Alloc &allocator) const
68 {
69 auto new_task(std::allocate_shared<Task<Func>>(
70 typename std::allocator_traits<Alloc>::template rebind_alloc<char>(allocator), std::move(function),
71 task_count_));
72 context_.post(new_task, task_count_);
73 }
74
79 void join() const
80 {
81 std::unique_lock<std::mutex> lock(context_.mutex_);
82 while (*task_count_ > 0)
83 if (!context_.execute_next(lock)) context_.condition_.wait(lock);
84 }
85
90
91private:
92 template <class Func>
93 struct Task : ThreadPoolContext::Function
94 {
95 explicit Task(Func func, const std::shared_ptr<size_t> &task_count) : function(std::move(func))
96 {
97 work_count_ = task_count;
98 execute_ = [](std::shared_ptr<ThreadPoolContext::Function> &p)
99 {
100 Func tmp(std::move(static_cast<Task *>(p.get())->function));
101 p.reset();
102 tmp();
103 };
104 }
105 Func function;
106 };
107
108 // cppcheck-suppress unusedPrivateFunction
109 void on_work_started()
110 {
111 std::lock_guard lock(context_.mutex_);
112 context_.do_work_started(task_count_);
113 }
114
115 // cppcheck-suppress unusedPrivateFunction
116 void on_work_finished()
117 {
118 std::lock_guard lock(context_.mutex_);
119 context_.do_work_finished(task_count_); // Locks.
120 }
121
122
126 template <class Func, class Alloc>
127 // cppcheck-suppress unusedPrivateFunction
128 [[maybe_unused]] void dispatch(Func, const Alloc &) const
129 {
130 }
131
135 template <class Func, class Alloc>
136 // cppcheck-suppress unusedPrivateFunction
137 [[maybe_unused]] void defer(Func, const Alloc &) const
138 {
139 }
140
141 ThreadPoolContext &context_;
142 std::shared_ptr<size_t> task_count_;
143};
144
145} // namespace knp::backends::cpu_executors
The ThreadPoolExecutor class is a definition of the interface to thread pool used for thread executio...
~ThreadPoolExecutor()
Blocking destructor that waits for all tasks to be completed.
ThreadPoolContext & context()
Get thread pool context.
void join() const
Wait for all tasks to finish.
void post(Func function, const Alloc &allocator) const
Use functions from the asio library.
ThreadPoolExecutor(ThreadPoolContext &context)
Construct pool executor.
Namespace for CPU backend executors.
Definition backend.h:50
Context for reusable thread pool class, a modified example from asio documentation.