Flow
Documentation for the Flow C++ Library
Loading...
Searching...
No Matches
flow_simple_thread_pool.h
Go to the documentation of this file.
1#pragma once
3#include "flow_thread_task.h"
4#include "flow_vector.h"
5
6#include <future>
7#include <thread>
8
9namespace flow {
10
14 template <typename ThreadSafeQueue = ConcurrentQueue<ThreadTask>>
17 ThreadSafeQueue queue_;
18
19 public:
20 explicit SimpleThreadPool(std::size_t threadCount = std::thread::hardware_concurrency() - 1) {
21 threads_.reserve(threadCount);
22 for (std::size_t i = 0; i < threadCount; ++i) {
23 threads_.emplaceBack(std::bind(&SimpleThreadPool::runTasks, this, std::placeholders::_1));
24 }
25 }
26
28 std::size_t poolSize() const {
29 return threads_.size();
30 }
31
35 template <typename Callable, typename ...Args>
36 std::future<std::invoke_result_t<Callable, Args&&...>> submit(Callable callable, Args&&... args) {
37 using ReturnType = std::invoke_result_t<Callable, Args&&...>;
38 std::packaged_task<ReturnType()> task(std::bind(std::move(callable), std::forward<Args>(args)...));
39 auto result = task.get_future();
40 queue_.push(ThreadTask(std::move(task)));
41 return result;
42 }
43
48 if (auto task = queue_.tryPop(); task) {
49 task->execute();
50 } else {
51 std::this_thread::yield();
52 }
53 }
54
55 private:
56 void runTasks(std::stop_token token) {
57 while (!token.stop_requested()) {
59 }
60 }
61 };
62}
std::future< std::invoke_result_t< Callable, Args &&... > > submit(Callable callable, Args &&... args)
Submit a task to the thread pool queue.
void runTasks(std::stop_token token)
SimpleThreadPool(std::size_t threadCount=std::thread::hardware_concurrency() - 1)
flow::Vector< std::jthread > threads_
void runPendingTask()
Try run a task from the pool queue. If the queue is empty, then it yields the thread....
A task that can be execute by a thread. Internally, it uses type erasure to store a std::packaged_tas...