Callisto Engine
threading_module.h
Go to the documentation of this file.
1#pragma once
2
3#include <future>
4#include <utility>
5#include "../api_status.h"
6#include "init_threading_params.h"
7#include "type_aliases.h"
8#include "async_task.h"
9
15namespace cl::threading {
16 template <typename T> class async_result;
17 template <typename T> async_result<T> schedule_work(const typed_work<T>& work);
18
19 namespace internal {
26 template<typename T>
27 async_handler create_task_handler(const cl::threading::typed_work<T>& work);
28
34 async_handler create_task_handler(const cl::threading::typed_work<void>& work);
35 }
36
41 scheduler* get_scheduler();
42
50 api_status init(const init_threading_params& p);
51
57 api_status shutdown();
58
59 template <typename TIn>
61 private:
62 std::shared_future<TIn> future;
63
64 public:
65 explicit async_result(const std::shared_future<TIn>& future)
66 : future{future} {}
67
68 template <typename TOut>
69 async_result<TOut> then(typed_callback<TIn, TOut> f) const {
70 return schedule_work<TOut>([fut=future, f]() {
71 const auto value = fut.get();
72 return f(value);
73 });
74 }
75
76 TIn wait() const {
77 return future.get();
78 }
79 };
80
81 template <>
82 class async_result<void> {
83 private:
84 std::shared_future<void> future;
85
86 public:
87 explicit async_result(std::shared_future<void> future)
88 : future{std::move(future)} {}
89
90 template <typename TOut>
91 async_result<TOut> then(typed_void_callback<TOut> f) const {
92 return schedule_work<TOut>([fut=future, f]() {
93 fut.wait();
94 return f();
95 });
96 }
97
98 void wait() const {
99 future.wait();
100 }
101 };
102
103 template <typename T>
104 async_handler internal::create_task_handler(const cl::threading::typed_work<T>& work) {
105 return [work](async_task* t) {
106 auto value = work();
107 ((async_task_t<T>*)t)->promise.set_value(value);
108 };
109 }
110
111 template<typename T>
112 async_result<T> schedule_work(const cl::threading::typed_work<T>& work) {
113 using typed_task = async_task_t<T>;
114 auto task = std::make_unique<typed_task>();
115 auto future = task->promise.get_future();
116
117 // Set the work to be run on a separate thread
118 task->exec = internal::create_task_handler(work);
119
120 // Schedule the task on the next available thread
121 async_worker* w{nullptr};
122 const auto sched = get_scheduler();
123 sched->next(&w);
124 w->schedule(std::move(task));
125
126 return async_result<T>(future.share());
127 }
128}
Definition: threading_module.h:60
Definition: async_worker.h:7
Definition: async_task.h:11
Definition: async_task.h:6
async_handler create_task_handler(const cl::threading::typed_work< T > &work)
Definition: threading_module.h:104
scheduler * get_scheduler()
Get the active scheduler for the task pool.
Definition: threading_module.cpp:64