VOX
A little voxel engine
Loading...
Searching...
No Matches
ThreadPoolAccessor.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "logger.hpp"
4#include "ThreadPool.hpp"
5#include <functional>
6#include <unordered_set>
7
9{
10public:
13
18
26 template<typename F>
27 uint64_t submit(F && f)
28 {
29 std::lock_guard<std::mutex> lock(m_futures_mutex);
30
31 typedef typename std::invoke_result<F>::type result_type;
32 //create a packaged task with the function
33 std::shared_ptr<std::packaged_task<result_type()>> task_ptr = std::make_shared<std::packaged_task<result_type()>>(std::move(f));
34
35 //encapsulate inside another void function with error handling + id tracking
36 uint64_t id = m_counter++;
37 std::function<void()> wrapper_func = [task_ptr = std::move(task_ptr), this, id] () mutable
38 {
39 std::exception_ptr eptr = nullptr;
40
41 (*task_ptr)();
42
43 try
44 {
45 task_ptr->get_future().get();
46 }
47 catch (...)
48 {
49 eptr = std::current_exception();
50 }
51
52 {
53 std::lock_guard<std::mutex> lock(m_finished_tasks_mutex);
54 m_finished_tasks.insert(id);
55 }
56
57 if (eptr != nullptr)
58 std::rethrow_exception(eptr);
59 };
60
61 //submit the task to the thread pool
62 std::future<void> future_v = m_thread_pool.submit(wrapper_func);
63 m_futures.insert(std::make_pair(id, std::move(future_v)));
64
65 return id;
66 }
67
71 void waitForAll();
72
77
83 void waitForTask(uint64_t id);
84
90 void waitForTasks(const std::vector<uint64_t> & ids);
91private:
92 ThreadPool & m_thread_pool;
93 uint64_t m_counter = 0;
94
95 std::unordered_set<uint64_t> m_finished_tasks;
96 std::mutex m_finished_tasks_mutex;
97 std::unordered_map<uint64_t, std::future<void>> m_futures;
98 std::mutex m_futures_mutex;
99
106 void waitTask(uint64_t id);
107};
Definition: ThreadPoolAccessor.hpp:9
ThreadPoolAccessor & operator=(ThreadPoolAccessor &&)=delete
void waitForFinishedTasks()
wait for all finished task
Definition: ThreadPoolAccessor.cpp:22
uint64_t submit(F &&f)
Submit a task to the threadpool, the task will be executed asynchronously.
Definition: ThreadPoolAccessor.hpp:27
~ThreadPoolAccessor()
Definition: ThreadPoolAccessor.cpp:8
void waitForTask(uint64_t id)
wait for a specific task to finish
Definition: ThreadPoolAccessor.cpp:37
void waitForAll()
wait for all tasks to finish
Definition: ThreadPoolAccessor.cpp:13
ThreadPoolAccessor(const ThreadPoolAccessor &)=delete
ThreadPoolAccessor & operator=(const ThreadPoolAccessor &)=delete
ThreadPoolAccessor()
Definition: ThreadPoolAccessor.cpp:3
void waitForTasks(const std::vector< uint64_t > &ids)
wait for a list of tasks to finish
Definition: ThreadPoolAccessor.cpp:43
ThreadPoolAccessor(ThreadPoolAccessor &&)=delete
Definition: ThreadPool.hpp:16
std::future< void > submit(std::function< void()> f)
Definition: ThreadPool.hpp:26