基于C++ Coroutines提案 ‘Stackless Resumable Functions’编写的协程库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_async_modern_cb.cpp 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. #include "librf.h"
  2. #include <chrono>
  3. #include <iostream>
  4. #include <string>
  5. #include <thread>
  6. #include <future>
  7. template<typename _Input_t, typename _Callable_t>
  8. __declspec(noinline)
  9. void tostring_async_originalism(_Input_t&& value, _Callable_t&& callback)
  10. {
  11. std::thread([callback = std::move(callback), value = std::forward<_Input_t>(value)]
  12. {
  13. callback(std::to_string(value));
  14. }).detach();
  15. }
  16. //回调适配器的模板类
  17. //这个默认类以_Callable_t作为真正的回调
  18. //返回无意义的int,以便于编译通过
  19. template<typename _Callable_t, typename _Result_t>
  20. struct modern_callback_adapter_t
  21. {
  22. using return_type = int;
  23. using callback_type = _Callable_t;
  24. static std::tuple<callback_type, return_type> traits(_Callable_t&& callback)
  25. {
  26. return { std::forward<_Callable_t>(callback), 0 };
  27. }
  28. };
  29. #define MODERN_CALLBACK_TRAITS(type) \
  30. using _Result_t = type; \
  31. using _Adapter_t = modern_callback_adapter_t<std::decay_t<_Callable_t>, _Result_t>; \
  32. auto adapter = typename _Adapter_t::traits(std::forward<_Callable_t>(callback))
  33. #define MODERN_CALLBACK_CALL() callback = std::move(std::get<0>(adapter))
  34. #define MODERN_CALLBACK_RETURN() return std::move(std::get<1>(adapter))
  35. template<typename _Input_t, typename _Callable_t>
  36. auto tostring_async_macro(_Input_t&& value, _Callable_t&& callback)
  37. {
  38. MODERN_CALLBACK_TRAITS(std::string);
  39. std::thread([MODERN_CALLBACK_CALL(), value = std::forward<_Input_t>(value)]
  40. {
  41. callback(std::to_string(value));
  42. }).detach();
  43. MODERN_CALLBACK_RETURN();
  44. }
  45. //演示如何通过回调适配器模型,将异步回调,扩展到支持future模式,调用链模式,以及协程。
  46. //
  47. //一个使用回调处理结果的异步函数,会涉及五个概念:
  48. //_Input_t:异步函数的输入参数;
  49. //_Callable_t:回调函数,这个回调,必须调用一次,且只能调用一次;
  50. //_Return_t:异步函数的返回值;
  51. //_Result_t:异步函数完成后的结果值,作为回调函数的入参部分;这个参数可以有零至多个;
  52. //_Exception_t:回调函数的异常, 如果不喜欢异常的则忽略这个部分,但就得异步代码将异常处置妥当;
  53. //
  54. //在回调适配器模型里,_Input_t/_Result_t/_Exception_t(可选)是异步函数提供的功能所固有的部分;_Callable_t/_Return_t
  55. //部分并不直接使用,而是通过适配器去另外处理。这样给予适配器一次扩展到future模式,调用链模式的机会,以及支持协程的机会。
  56. //
  57. //tostring_async 演示了在其他线程里,将_Input_t的输入值,转化为std::string类型的_Result_t。
  58. //然后调用void(std::string &&)类型的_Callable_t。忽视异常处理。
  59. //
  60. template<typename _Input_t, typename _Callable_t>
  61. __declspec(noinline)
  62. auto tostring_async(_Input_t&& value, _Callable_t&& callback)
  63. //-> typename modern_callback_adapter_t<std::decay_t<_Callable_t>, std::string>::return_type
  64. {
  65. using _Result_t = std::string;
  66. //适配器类型
  67. using _Adapter_t = modern_callback_adapter_t<std::decay_t<_Callable_t>, _Result_t>;
  68. //通过适配器获得兼容_Callable_t类型的真正的回调,以及返回值_Return_t
  69. auto adapter = typename _Adapter_t::traits(std::forward<_Callable_t>(callback));
  70. //real_callback与callback未必是同一个变量,甚至未必是同一个类型
  71. std::thread([real_callback = std::move(std::get<0>(adapter)), value = std::forward<_Input_t>(value)]
  72. {
  73. real_callback(std::to_string(value));
  74. }).detach();
  75. //返回适配器的return_type变量
  76. return std::move(std::get<1>(adapter));
  77. }
  78. template<typename _Input_t>
  79. auto tostring_async_future(_Input_t&& value)
  80. {
  81. std::promise<std::string> _promise;
  82. std::future<std::string> _future = _promise.get_future();
  83. std::thread([_promise = std::move(_promise), value = std::forward<_Input_t>(value)]() mutable
  84. {
  85. _promise.set_value(std::to_string(value));
  86. }).detach();
  87. return std::move(_future);
  88. }
  89. //-------------------------------------------------------------------------------------------------
  90. //下面演示如何扩展tostring_async函数,以支持future模式
  91. //一、做一个辅助类
  92. struct use_future_t {};
  93. //二、申明这个辅助类的全局变量。不什么这个变量也行,就是每次要写use_future_t{},麻烦些
  94. //以后就使用use_future,替代tostring_async的callback参数了。
  95. //这个参数其实不需要实质传参,最后会被编译器优化没了。
  96. //仅仅是要指定_Callable_t的类型为use_future_t,
  97. //从而在tostring_async函数内,使用偏特化的modern_callback_adapter_t<use_future_t, ...>而已。
  98. inline constexpr use_future_t use_future{};
  99. //将替换use_future_t的,真正的回调类。
  100. //此回调类,符合tostring_async的_Callable_t函数签名。生成此类的实例作为real_callback交给tostring_async作为异步回调。
  101. //
  102. //future模式下,此类持有一个std::promise<_Result_t>,便于设置值和异常
  103. //而将与promise关联的future作为返回值_Return_t,让tostring_async返回。
  104. template<typename _Result_t>
  105. struct use_future_callback_t
  106. {
  107. using promise_type = std::promise<_Result_t>;
  108. mutable promise_type _promise;
  109. void operator()(_Result_t&& value) const
  110. {
  111. _promise.set_value(value);
  112. }
  113. void operator()(_Result_t&& value, std::exception_ptr&& eptr) const
  114. {
  115. if (eptr != nullptr)
  116. _promise.set_exception(std::forward<std::exception_ptr>(eptr));
  117. else
  118. _promise.set_value(std::forward<_Result_t>(value));
  119. }
  120. };
  121. //偏特化_Callable_t为use_future_t类型的modern_callback_adapter_t
  122. //真正的回调类型是use_future_callback_t,返回类型_Return_t是std::future<_Result_t>。
  123. //配合use_future_callback_t的std::promise<_Result_t>,正好组成一对promise/future对。
  124. //promise在真正的回调里设置结果值;
  125. //future返回给调用者获取结果值。
  126. template<typename _Result_t>
  127. struct modern_callback_adapter_t<use_future_t, _Result_t>
  128. {
  129. using return_type = std::future<_Result_t>;
  130. using callback_type = use_future_callback_t<_Result_t>;
  131. static std::tuple<callback_type, return_type> traits(const use_future_t&/*没人关心这个变量*/)
  132. {
  133. callback_type real_callback{};
  134. return_type future = real_callback._promise.get_future();
  135. return { std::move(real_callback), std::move(future) };
  136. }
  137. };
  138. //-------------------------------------------------------------------------------------------------
  139. //同理,可以制作支持C++20的协程的下列一系列类(其实,这才是我的最终目的)
  140. struct use_awaitable_t {};
  141. inline constexpr use_awaitable_t use_awaitable{};
  142. template<typename _Result_t>
  143. struct use_awaitable_callback_t
  144. {
  145. using promise_type = resumef::promise_t<_Result_t>;
  146. using state_type = typename promise_type::state_type;
  147. resumef::counted_ptr<state_type> _state;
  148. void operator()(_Result_t&& value) const
  149. {
  150. _state->set_value(std::forward<_Result_t>(value));
  151. }
  152. void operator()(_Result_t&& value, std::exception_ptr&& eptr) const
  153. {
  154. if (eptr != nullptr)
  155. _state->set_exception(std::forward<std::exception_ptr>(eptr));
  156. else
  157. _state->set_value(std::forward<_Result_t>(value));
  158. }
  159. };
  160. template<typename _Result_t>
  161. struct modern_callback_adapter_t<use_awaitable_t, _Result_t>
  162. {
  163. using promise_type = resumef::promise_t<_Result_t>;
  164. using return_type = resumef::future_t<_Result_t>;
  165. using callback_type = use_awaitable_callback_t<_Result_t>;
  166. static std::tuple<callback_type, return_type> traits(const use_awaitable_t&)
  167. {
  168. promise_type promise;
  169. return { callback_type{ promise._state }, promise.get_future() };
  170. }
  171. };
  172. //所以,我现在的看法是,支持异步操作的库,尽可能如此设计回调。这样便于支持C++20的协程。以及future::then这样的任务链。
  173. //这才是“摩登C++”!
  174. //使用范例
  175. __declspec(noinline)
  176. void resumable_main_modern_cb()
  177. {
  178. using namespace std::literals;
  179. //使用lambda作为异步回调函数,传统用法
  180. //tostring_async_originalism(-1.0, [](std::string && value)
  181. // {
  182. // std::cout << value << std::endl;
  183. // });
  184. tostring_async(1.0, [](std::string && value)
  185. {
  186. std::cout << value << std::endl;
  187. });
  188. /*
  189. std::cout << nocare << std::endl;
  190. std::this_thread::sleep_for(1s);
  191. std::cout << "......" << std::endl;
  192. //支持future的用法
  193. std::future<std::string> f1 = tostring_async_future(5);
  194. std::cout << f1.get() << std::endl;
  195. std::future<std::string> f2 = tostring_async(6.0f, use_future);
  196. std::cout << f2.get() << std::endl;
  197. //支持librf的用法
  198. GO
  199. {
  200. std::string result = co_await tostring_async(10.0, use_awaitable);
  201. std::cout << result << std::endl;
  202. };
  203. resumef::this_scheduler()->run_until_notask();
  204. */
  205. }