simple thread
task.hpp
1 //SPDX-License-Identifier: LicenseRef-Apache-License-2.0
2 //Author: Blayne Dennis
3 
4 #ifndef __SIMPLE_THREADING_TASK__
5 #define __SIMPLE_THREADING_TASK__
6 
7 #include <functional>
8 
9 #include "utility.hpp"
10 #include "context.hpp"
11 #include "data.hpp"
12 
13 namespace st {
14 namespace detail {
15 namespace task {
16 
17 struct context {
18  context() : evaluate([&]() -> data& { return m_result; }) { }
19 
20  template <typename Callable, typename... As>
21  context(Callable&& cb, As&&... as) {
22  using isv = typename std::is_void<detail::function_return_type<Callable,As...>>;
23  evaluate = create_function(
24  std::integral_constant<bool,isv::value>(),
25  std::forward<Callable>(cb),
26  std::forward<As>(as)...);
27  }
28 
29  // handle case where Callable returns void
30  template <typename Callable, typename... As>
31  std::function<data&()>
32  create_function(std::true_type, Callable&& cb, As&&... as) {
33  return [=]() mutable -> data& {
34  if(!(this->m_flag)) {
35  this->m_flag = true;
36  cb(std::forward<As>(as)...);
37  }
38 
39  return this->m_result; // return empty data
40  };
41  }
42 
43  // handle case where Callable returns some value
44  template <typename Callable, typename... As>
45  std::function<data&()>
46  create_function(std::false_type, Callable&& cb, As&&... as) {
47  return [=]() mutable -> data& {
48  if(!(this->m_flag)) {
49  this->m_flag = true;
50  typedef detail::function_return_type<Callable,As...> R;
51  this->m_result = data::make<R>(cb(std::forward<As>(as)...));
52  }
53 
54  return this->m_result;
55  };
56  }
57 
58 
59  bool m_flag = false;
60  data m_result;
61  std::function<data&()> evaluate;
62 };
63 
64 }
65 }
66 
88 struct task : public st::shared_context<task, detail::task::context> {
89  inline virtual ~task() { }
90 
96  template <typename... As>
97  static task make(As&&... as) {
98  task t;
99  t.ctx(std::make_shared<detail::task::context>(std::forward<As>(as)...));
100  return t;
101  }
102 
103  inline data& operator()() {
104  if(!ctx()) {
105  ctx(std::make_shared<detail::task::context>());
106  }
107 
108  return ctx()->evaluate();
109  }
110 };
111 
112 }
113 
114 #endif
type erased data container
Definition: data.hpp:24
CRTP-templated interface to provide shared context api.
Definition: context.hpp:43
std::shared_ptr< detail::task::context > & ctx() const
Definition: context.hpp:50
wrap any Callable and optional arguments into an executable task
Definition: task.hpp:88
static task make(As &&... as)
wrap an arbitrary Callable and optional arguments in a task
Definition: task.hpp:97