co_spawn.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  1. //
  2. // impl/co_spawn.hpp
  3. // ~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2023 Christopher M. Kohlhoff (chris at kohlhoff dot com)
  6. //
  7. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  8. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  9. //
  10. #ifndef BOOST_ASIO_IMPL_CO_SPAWN_HPP
  11. #define BOOST_ASIO_IMPL_CO_SPAWN_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include <boost/asio/detail/config.hpp>
  16. #include <boost/asio/associated_cancellation_slot.hpp>
  17. #include <boost/asio/awaitable.hpp>
  18. #include <boost/asio/detail/memory.hpp>
  19. #include <boost/asio/detail/recycling_allocator.hpp>
  20. #include <boost/asio/dispatch.hpp>
  21. #include <boost/asio/execution/outstanding_work.hpp>
  22. #include <boost/asio/post.hpp>
  23. #include <boost/asio/prefer.hpp>
  24. #include <boost/asio/use_awaitable.hpp>
  25. #include <boost/asio/detail/push_options.hpp>
  26. namespace boost {
  27. namespace asio {
  28. namespace detail {
  29. template <typename Executor, typename = void>
  30. class co_spawn_work_guard
  31. {
  32. public:
  33. typedef decay_t<
  34. prefer_result_t<Executor,
  35. execution::outstanding_work_t::tracked_t
  36. >
  37. > executor_type;
  38. co_spawn_work_guard(const Executor& ex)
  39. : executor_(boost::asio::prefer(ex, execution::outstanding_work.tracked))
  40. {
  41. }
  42. executor_type get_executor() const noexcept
  43. {
  44. return executor_;
  45. }
  46. private:
  47. executor_type executor_;
  48. };
  49. #if !defined(BOOST_ASIO_NO_TS_EXECUTORS)
  50. template <typename Executor>
  51. struct co_spawn_work_guard<Executor,
  52. enable_if_t<
  53. !execution::is_executor<Executor>::value
  54. >> : executor_work_guard<Executor>
  55. {
  56. co_spawn_work_guard(const Executor& ex)
  57. : executor_work_guard<Executor>(ex)
  58. {
  59. }
  60. };
  61. #endif // !defined(BOOST_ASIO_NO_TS_EXECUTORS)
  62. template <typename Handler, typename Executor,
  63. typename Function, typename = void>
  64. struct co_spawn_state
  65. {
  66. template <typename H, typename F>
  67. co_spawn_state(H&& h, const Executor& ex, F&& f)
  68. : handler(std::forward<H>(h)),
  69. spawn_work(ex),
  70. handler_work(boost::asio::get_associated_executor(handler, ex)),
  71. function(std::forward<F>(f))
  72. {
  73. }
  74. Handler handler;
  75. co_spawn_work_guard<Executor> spawn_work;
  76. co_spawn_work_guard<associated_executor_t<Handler, Executor>> handler_work;
  77. Function function;
  78. };
  79. template <typename Handler, typename Executor, typename Function>
  80. struct co_spawn_state<Handler, Executor, Function,
  81. enable_if_t<
  82. is_same<
  83. typename associated_executor<Handler,
  84. Executor>::asio_associated_executor_is_unspecialised,
  85. void
  86. >::value
  87. >>
  88. {
  89. template <typename H, typename F>
  90. co_spawn_state(H&& h, const Executor& ex, F&& f)
  91. : handler(std::forward<H>(h)),
  92. handler_work(ex),
  93. function(std::forward<F>(f))
  94. {
  95. }
  96. Handler handler;
  97. co_spawn_work_guard<Executor> handler_work;
  98. Function function;
  99. };
  100. struct co_spawn_dispatch
  101. {
  102. template <typename CompletionToken>
  103. auto operator()(CompletionToken&& token) const
  104. -> decltype(boost::asio::dispatch(std::forward<CompletionToken>(token)))
  105. {
  106. return boost::asio::dispatch(std::forward<CompletionToken>(token));
  107. }
  108. };
  109. struct co_spawn_post
  110. {
  111. template <typename CompletionToken>
  112. auto operator()(CompletionToken&& token) const
  113. -> decltype(boost::asio::post(std::forward<CompletionToken>(token)))
  114. {
  115. return boost::asio::post(std::forward<CompletionToken>(token));
  116. }
  117. };
  118. template <typename T, typename Handler, typename Executor, typename Function>
  119. awaitable<awaitable_thread_entry_point, Executor> co_spawn_entry_point(
  120. awaitable<T, Executor>*, co_spawn_state<Handler, Executor, Function> s)
  121. {
  122. (void) co_await co_spawn_dispatch{};
  123. (co_await awaitable_thread_has_context_switched{}) = false;
  124. std::exception_ptr e = nullptr;
  125. bool done = false;
  126. try
  127. {
  128. T t = co_await s.function();
  129. done = true;
  130. bool switched = (co_await awaitable_thread_has_context_switched{});
  131. if (!switched)
  132. (void) co_await co_spawn_post();
  133. (dispatch)(s.handler_work.get_executor(),
  134. [handler = std::move(s.handler), t = std::move(t)]() mutable
  135. {
  136. std::move(handler)(std::exception_ptr(), std::move(t));
  137. });
  138. co_return;
  139. }
  140. catch (...)
  141. {
  142. if (done)
  143. throw;
  144. e = std::current_exception();
  145. }
  146. bool switched = (co_await awaitable_thread_has_context_switched{});
  147. if (!switched)
  148. (void) co_await co_spawn_post();
  149. (dispatch)(s.handler_work.get_executor(),
  150. [handler = std::move(s.handler), e]() mutable
  151. {
  152. std::move(handler)(e, T());
  153. });
  154. }
  155. template <typename Handler, typename Executor, typename Function>
  156. awaitable<awaitable_thread_entry_point, Executor> co_spawn_entry_point(
  157. awaitable<void, Executor>*, co_spawn_state<Handler, Executor, Function> s)
  158. {
  159. (void) co_await co_spawn_dispatch{};
  160. (co_await awaitable_thread_has_context_switched{}) = false;
  161. std::exception_ptr e = nullptr;
  162. try
  163. {
  164. co_await s.function();
  165. }
  166. catch (...)
  167. {
  168. e = std::current_exception();
  169. }
  170. bool switched = (co_await awaitable_thread_has_context_switched{});
  171. if (!switched)
  172. (void) co_await co_spawn_post();
  173. (dispatch)(s.handler_work.get_executor(),
  174. [handler = std::move(s.handler), e]() mutable
  175. {
  176. std::move(handler)(e);
  177. });
  178. }
  179. template <typename T, typename Executor>
  180. class awaitable_as_function
  181. {
  182. public:
  183. explicit awaitable_as_function(awaitable<T, Executor>&& a)
  184. : awaitable_(std::move(a))
  185. {
  186. }
  187. awaitable<T, Executor> operator()()
  188. {
  189. return std::move(awaitable_);
  190. }
  191. private:
  192. awaitable<T, Executor> awaitable_;
  193. };
  194. template <typename Handler, typename Executor, typename = void>
  195. class co_spawn_cancellation_handler
  196. {
  197. public:
  198. co_spawn_cancellation_handler(const Handler&, const Executor& ex)
  199. : signal_(detail::allocate_shared<cancellation_signal>(
  200. detail::recycling_allocator<cancellation_signal,
  201. detail::thread_info_base::cancellation_signal_tag>())),
  202. ex_(ex)
  203. {
  204. }
  205. cancellation_slot slot()
  206. {
  207. return signal_->slot();
  208. }
  209. void operator()(cancellation_type_t type)
  210. {
  211. shared_ptr<cancellation_signal> sig = signal_;
  212. boost::asio::dispatch(ex_, [sig, type]{ sig->emit(type); });
  213. }
  214. private:
  215. shared_ptr<cancellation_signal> signal_;
  216. Executor ex_;
  217. };
  218. template <typename Handler, typename Executor>
  219. class co_spawn_cancellation_handler<Handler, Executor,
  220. enable_if_t<
  221. is_same<
  222. typename associated_executor<Handler,
  223. Executor>::asio_associated_executor_is_unspecialised,
  224. void
  225. >::value
  226. >>
  227. {
  228. public:
  229. co_spawn_cancellation_handler(const Handler&, const Executor&)
  230. {
  231. }
  232. cancellation_slot slot()
  233. {
  234. return signal_.slot();
  235. }
  236. void operator()(cancellation_type_t type)
  237. {
  238. signal_.emit(type);
  239. }
  240. private:
  241. cancellation_signal signal_;
  242. };
  243. template <typename Executor>
  244. class initiate_co_spawn
  245. {
  246. public:
  247. typedef Executor executor_type;
  248. template <typename OtherExecutor>
  249. explicit initiate_co_spawn(const OtherExecutor& ex)
  250. : ex_(ex)
  251. {
  252. }
  253. executor_type get_executor() const noexcept
  254. {
  255. return ex_;
  256. }
  257. template <typename Handler, typename F>
  258. void operator()(Handler&& handler, F&& f) const
  259. {
  260. typedef result_of_t<F()> awaitable_type;
  261. typedef decay_t<Handler> handler_type;
  262. typedef decay_t<F> function_type;
  263. typedef co_spawn_cancellation_handler<
  264. handler_type, Executor> cancel_handler_type;
  265. auto slot = boost::asio::get_associated_cancellation_slot(handler);
  266. cancel_handler_type* cancel_handler = slot.is_connected()
  267. ? &slot.template emplace<cancel_handler_type>(handler, ex_)
  268. : nullptr;
  269. cancellation_slot proxy_slot(
  270. cancel_handler
  271. ? cancel_handler->slot()
  272. : cancellation_slot());
  273. cancellation_state cancel_state(proxy_slot);
  274. auto a = (co_spawn_entry_point)(static_cast<awaitable_type*>(nullptr),
  275. co_spawn_state<handler_type, Executor, function_type>(
  276. std::forward<Handler>(handler), ex_, std::forward<F>(f)));
  277. awaitable_handler<executor_type, void>(std::move(a),
  278. ex_, proxy_slot, cancel_state).launch();
  279. }
  280. private:
  281. Executor ex_;
  282. };
  283. } // namespace detail
  284. template <typename Executor, typename T, typename AwaitableExecutor,
  285. BOOST_ASIO_COMPLETION_TOKEN_FOR(
  286. void(std::exception_ptr, T)) CompletionToken>
  287. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
  288. CompletionToken, void(std::exception_ptr, T))
  289. co_spawn(const Executor& ex,
  290. awaitable<T, AwaitableExecutor> a, CompletionToken&& token,
  291. constraint_t<
  292. (is_executor<Executor>::value || execution::is_executor<Executor>::value)
  293. && is_convertible<Executor, AwaitableExecutor>::value
  294. >)
  295. {
  296. return async_initiate<CompletionToken, void(std::exception_ptr, T)>(
  297. detail::initiate_co_spawn<AwaitableExecutor>(AwaitableExecutor(ex)),
  298. token, detail::awaitable_as_function<T, AwaitableExecutor>(std::move(a)));
  299. }
  300. template <typename Executor, typename AwaitableExecutor,
  301. BOOST_ASIO_COMPLETION_TOKEN_FOR(
  302. void(std::exception_ptr)) CompletionToken>
  303. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
  304. CompletionToken, void(std::exception_ptr))
  305. co_spawn(const Executor& ex,
  306. awaitable<void, AwaitableExecutor> a, CompletionToken&& token,
  307. constraint_t<
  308. (is_executor<Executor>::value || execution::is_executor<Executor>::value)
  309. && is_convertible<Executor, AwaitableExecutor>::value
  310. >)
  311. {
  312. return async_initiate<CompletionToken, void(std::exception_ptr)>(
  313. detail::initiate_co_spawn<AwaitableExecutor>(AwaitableExecutor(ex)),
  314. token, detail::awaitable_as_function<
  315. void, AwaitableExecutor>(std::move(a)));
  316. }
  317. template <typename ExecutionContext, typename T, typename AwaitableExecutor,
  318. BOOST_ASIO_COMPLETION_TOKEN_FOR(
  319. void(std::exception_ptr, T)) CompletionToken>
  320. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
  321. CompletionToken, void(std::exception_ptr, T))
  322. co_spawn(ExecutionContext& ctx,
  323. awaitable<T, AwaitableExecutor> a, CompletionToken&& token,
  324. constraint_t<
  325. is_convertible<ExecutionContext&, execution_context&>::value
  326. && is_convertible<typename ExecutionContext::executor_type,
  327. AwaitableExecutor>::value
  328. >)
  329. {
  330. return (co_spawn)(ctx.get_executor(), std::move(a),
  331. std::forward<CompletionToken>(token));
  332. }
  333. template <typename ExecutionContext, typename AwaitableExecutor,
  334. BOOST_ASIO_COMPLETION_TOKEN_FOR(
  335. void(std::exception_ptr)) CompletionToken>
  336. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
  337. CompletionToken, void(std::exception_ptr))
  338. co_spawn(ExecutionContext& ctx,
  339. awaitable<void, AwaitableExecutor> a, CompletionToken&& token,
  340. constraint_t<
  341. is_convertible<ExecutionContext&, execution_context&>::value
  342. && is_convertible<typename ExecutionContext::executor_type,
  343. AwaitableExecutor>::value
  344. >)
  345. {
  346. return (co_spawn)(ctx.get_executor(), std::move(a),
  347. std::forward<CompletionToken>(token));
  348. }
  349. template <typename Executor, typename F,
  350. BOOST_ASIO_COMPLETION_TOKEN_FOR(typename detail::awaitable_signature<
  351. result_of_t<F()>>::type) CompletionToken>
  352. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken,
  353. typename detail::awaitable_signature<result_of_t<F()>>::type)
  354. co_spawn(const Executor& ex, F&& f, CompletionToken&& token,
  355. constraint_t<
  356. is_executor<Executor>::value || execution::is_executor<Executor>::value
  357. >)
  358. {
  359. return async_initiate<CompletionToken,
  360. typename detail::awaitable_signature<result_of_t<F()>>::type>(
  361. detail::initiate_co_spawn<
  362. typename result_of_t<F()>::executor_type>(ex),
  363. token, std::forward<F>(f));
  364. }
  365. template <typename ExecutionContext, typename F,
  366. BOOST_ASIO_COMPLETION_TOKEN_FOR(typename detail::awaitable_signature<
  367. result_of_t<F()>>::type) CompletionToken>
  368. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken,
  369. typename detail::awaitable_signature<result_of_t<F()>>::type)
  370. co_spawn(ExecutionContext& ctx, F&& f, CompletionToken&& token,
  371. constraint_t<
  372. is_convertible<ExecutionContext&, execution_context&>::value
  373. >)
  374. {
  375. return (co_spawn)(ctx.get_executor(), std::forward<F>(f),
  376. std::forward<CompletionToken>(token));
  377. }
  378. } // namespace asio
  379. } // namespace boost
  380. #include <boost/asio/detail/pop_options.hpp>
  381. #endif // BOOST_ASIO_IMPL_CO_SPAWN_HPP