librf
rf_task.h
1 #pragma once
2 
3 namespace resumef
4 {
5 #ifndef DOXYGEN_SKIP_PROPERTY
6 
17  struct task_t
18  {
19  task_t();
20  virtual ~task_t();
21 
22  protected:
23  friend scheduler_t;
24  counted_ptr<state_base_t> _state;
25  };
26 #endif
27 
28  //----------------------------------------------------------------------------------------------
29 
30  template<class _Ty, class = std::void_t<>>
31  struct task_impl_t;
32 
33 #ifndef DOXYGEN_SKIP_PROPERTY
34  template<class _Ty>
35  struct task_impl_t<_Ty, std::void_t<traits::is_future<std::remove_reference_t<_Ty>>>> : public task_t
36  {
37  using future_type = std::remove_reference_t<_Ty>;
38  using value_type = typename future_type::value_type;
39  using state_type = state_t<value_type>;
40 
41  task_impl_t() = default;
42  task_impl_t(future_type& f)
43  {
44  initialize(f);
45  }
46  protected:
47  void initialize(future_type& f)
48  {
49  _state = f._state.get();
50  }
51  };
52 
53  template<class _Ty>
54  struct task_impl_t<generator_t<_Ty>> : public task_t
55  {
56  using value_type = _Ty;
57  using future_type = generator_t<value_type>;
58  using state_type = state_generator_t;
59 
60  task_impl_t() = default;
61  task_impl_t(future_type& f)
62  {
63  initialize(f);
64  }
65  protected:
66  void initialize(future_type& f)
67  {
68  _state = f.detach_state();
69  }
70  };
71 
72  //----------------------------------------------------------------------------------------------
73 
74  //ctx_task_t接受的是一个'函数对象'
75  //这个'函数对象'被调用后,返回generator<_Ty>/future_t<_Ty>类型
76  //然后'函数对象'作为异步执行的上下文状态保存起来
77  template<class _Ctx>
78  struct task_ctx_impl_t : public task_impl_t<remove_cvref_t<decltype(std::declval<_Ctx>()())>>
79  {
80  using context_type = _Ctx;
81 
82  context_type _context;
83 
84  task_ctx_impl_t(context_type ctx)
85  : _context(std::move(ctx))
86  {
87  decltype(auto) f = _context();
88  this->initialize(f);
89  }
90  };
91 #endif //DOXYGEN_SKIP_PROPERTY
92 }