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