co_spawn.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. //
  2. // impl/co_spawn.hpp
  3. // ~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2024 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. #if !defined(BOOST_ASIO_NO_EXCEPTIONS)
  127. try
  128. #endif // !defined(BOOST_ASIO_NO_EXCEPTIONS)
  129. {
  130. T t = co_await s.function();
  131. done = true;
  132. bool switched = (co_await awaitable_thread_has_context_switched{});
  133. if (!switched)
  134. {
  135. co_await this_coro::throw_if_cancelled(false);
  136. (void) co_await co_spawn_post();
  137. }
  138. (dispatch)(s.handler_work.get_executor(),
  139. [handler = std::move(s.handler), t = std::move(t)]() mutable
  140. {
  141. std::move(handler)(std::exception_ptr(), std::move(t));
  142. });
  143. co_return;
  144. }
  145. #if !defined(BOOST_ASIO_NO_EXCEPTIONS)
  146. catch (...)
  147. {
  148. if (done)
  149. throw;
  150. e = std::current_exception();
  151. }
  152. #endif // !defined(BOOST_ASIO_NO_EXCEPTIONS)
  153. bool switched = (co_await awaitable_thread_has_context_switched{});
  154. if (!switched)
  155. {
  156. co_await this_coro::throw_if_cancelled(false);
  157. (void) co_await co_spawn_post();
  158. }
  159. (dispatch)(s.handler_work.get_executor(),
  160. [handler = std::move(s.handler), e]() mutable
  161. {
  162. std::move(handler)(e, T());
  163. });
  164. }
  165. template <typename Handler, typename Executor, typename Function>
  166. awaitable<awaitable_thread_entry_point, Executor> co_spawn_entry_point(
  167. awaitable<void, Executor>*, co_spawn_state<Handler, Executor, Function> s)
  168. {
  169. (void) co_await co_spawn_dispatch{};
  170. (co_await awaitable_thread_has_context_switched{}) = false;
  171. std::exception_ptr e = nullptr;
  172. #if !defined(BOOST_ASIO_NO_EXCEPTIONS)
  173. try
  174. #endif // !defined(BOOST_ASIO_NO_EXCEPTIONS)
  175. {
  176. co_await s.function();
  177. }
  178. #if !defined(BOOST_ASIO_NO_EXCEPTIONS)
  179. catch (...)
  180. {
  181. e = std::current_exception();
  182. }
  183. #endif // !defined(BOOST_ASIO_NO_EXCEPTIONS)
  184. bool switched = (co_await awaitable_thread_has_context_switched{});
  185. if (!switched)
  186. {
  187. co_await this_coro::throw_if_cancelled(false);
  188. (void) co_await co_spawn_post();
  189. }
  190. (dispatch)(s.handler_work.get_executor(),
  191. [handler = std::move(s.handler), e]() mutable
  192. {
  193. std::move(handler)(e);
  194. });
  195. }
  196. template <typename T, typename Executor>
  197. class awaitable_as_function
  198. {
  199. public:
  200. explicit awaitable_as_function(awaitable<T, Executor>&& a)
  201. : awaitable_(std::move(a))
  202. {
  203. }
  204. awaitable<T, Executor> operator()()
  205. {
  206. return std::move(awaitable_);
  207. }
  208. private:
  209. awaitable<T, Executor> awaitable_;
  210. };
  211. template <typename Handler, typename Executor, typename = void>
  212. class co_spawn_cancellation_handler
  213. {
  214. public:
  215. co_spawn_cancellation_handler(const Handler&, const Executor& ex)
  216. : signal_(detail::allocate_shared<cancellation_signal>(
  217. detail::recycling_allocator<cancellation_signal,
  218. detail::thread_info_base::cancellation_signal_tag>())),
  219. ex_(ex)
  220. {
  221. }
  222. cancellation_slot slot()
  223. {
  224. return signal_->slot();
  225. }
  226. void operator()(cancellation_type_t type)
  227. {
  228. shared_ptr<cancellation_signal> sig = signal_;
  229. boost::asio::dispatch(ex_, [sig, type]{ sig->emit(type); });
  230. }
  231. private:
  232. shared_ptr<cancellation_signal> signal_;
  233. Executor ex_;
  234. };
  235. template <typename Handler, typename Executor>
  236. class co_spawn_cancellation_handler<Handler, Executor,
  237. enable_if_t<
  238. is_same<
  239. typename associated_executor<Handler,
  240. Executor>::asio_associated_executor_is_unspecialised,
  241. void
  242. >::value
  243. >>
  244. {
  245. public:
  246. co_spawn_cancellation_handler(const Handler&, const Executor&)
  247. {
  248. }
  249. cancellation_slot slot()
  250. {
  251. return signal_.slot();
  252. }
  253. void operator()(cancellation_type_t type)
  254. {
  255. signal_.emit(type);
  256. }
  257. private:
  258. cancellation_signal signal_;
  259. };
  260. template <typename Executor>
  261. class initiate_co_spawn
  262. {
  263. public:
  264. typedef Executor executor_type;
  265. template <typename OtherExecutor>
  266. explicit initiate_co_spawn(const OtherExecutor& ex)
  267. : ex_(ex)
  268. {
  269. }
  270. executor_type get_executor() const noexcept
  271. {
  272. return ex_;
  273. }
  274. template <typename Handler, typename F>
  275. void operator()(Handler&& handler, F&& f) const
  276. {
  277. typedef result_of_t<F()> awaitable_type;
  278. typedef decay_t<Handler> handler_type;
  279. typedef decay_t<F> function_type;
  280. typedef co_spawn_cancellation_handler<
  281. handler_type, Executor> cancel_handler_type;
  282. auto slot = boost::asio::get_associated_cancellation_slot(handler);
  283. cancel_handler_type* cancel_handler = slot.is_connected()
  284. ? &slot.template emplace<cancel_handler_type>(handler, ex_)
  285. : nullptr;
  286. cancellation_slot proxy_slot(
  287. cancel_handler
  288. ? cancel_handler->slot()
  289. : cancellation_slot());
  290. cancellation_state cancel_state(proxy_slot);
  291. auto a = (co_spawn_entry_point)(static_cast<awaitable_type*>(nullptr),
  292. co_spawn_state<handler_type, Executor, function_type>(
  293. std::forward<Handler>(handler), ex_, std::forward<F>(f)));
  294. awaitable_handler<executor_type, void>(std::move(a),
  295. ex_, proxy_slot, cancel_state).launch();
  296. }
  297. private:
  298. Executor ex_;
  299. };
  300. } // namespace detail
  301. template <typename Executor, typename T, typename AwaitableExecutor,
  302. BOOST_ASIO_COMPLETION_TOKEN_FOR(
  303. void(std::exception_ptr, T)) CompletionToken>
  304. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
  305. CompletionToken, void(std::exception_ptr, T))
  306. co_spawn(const Executor& ex,
  307. awaitable<T, AwaitableExecutor> a, CompletionToken&& token,
  308. constraint_t<
  309. (is_executor<Executor>::value || execution::is_executor<Executor>::value)
  310. && is_convertible<Executor, AwaitableExecutor>::value
  311. >)
  312. {
  313. return async_initiate<CompletionToken, void(std::exception_ptr, T)>(
  314. detail::initiate_co_spawn<AwaitableExecutor>(AwaitableExecutor(ex)),
  315. token, detail::awaitable_as_function<T, AwaitableExecutor>(std::move(a)));
  316. }
  317. template <typename Executor, typename AwaitableExecutor,
  318. BOOST_ASIO_COMPLETION_TOKEN_FOR(
  319. void(std::exception_ptr)) CompletionToken>
  320. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
  321. CompletionToken, void(std::exception_ptr))
  322. co_spawn(const Executor& ex,
  323. awaitable<void, AwaitableExecutor> a, CompletionToken&& token,
  324. constraint_t<
  325. (is_executor<Executor>::value || execution::is_executor<Executor>::value)
  326. && is_convertible<Executor, AwaitableExecutor>::value
  327. >)
  328. {
  329. return async_initiate<CompletionToken, void(std::exception_ptr)>(
  330. detail::initiate_co_spawn<AwaitableExecutor>(AwaitableExecutor(ex)),
  331. token, detail::awaitable_as_function<
  332. void, AwaitableExecutor>(std::move(a)));
  333. }
  334. template <typename ExecutionContext, typename T, typename AwaitableExecutor,
  335. BOOST_ASIO_COMPLETION_TOKEN_FOR(
  336. void(std::exception_ptr, T)) CompletionToken>
  337. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
  338. CompletionToken, void(std::exception_ptr, T))
  339. co_spawn(ExecutionContext& ctx,
  340. awaitable<T, AwaitableExecutor> a, CompletionToken&& token,
  341. constraint_t<
  342. is_convertible<ExecutionContext&, execution_context&>::value
  343. && is_convertible<typename ExecutionContext::executor_type,
  344. AwaitableExecutor>::value
  345. >)
  346. {
  347. return (co_spawn)(ctx.get_executor(), std::move(a),
  348. std::forward<CompletionToken>(token));
  349. }
  350. template <typename ExecutionContext, typename AwaitableExecutor,
  351. BOOST_ASIO_COMPLETION_TOKEN_FOR(
  352. void(std::exception_ptr)) CompletionToken>
  353. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(
  354. CompletionToken, void(std::exception_ptr))
  355. co_spawn(ExecutionContext& ctx,
  356. awaitable<void, AwaitableExecutor> a, CompletionToken&& token,
  357. constraint_t<
  358. is_convertible<ExecutionContext&, execution_context&>::value
  359. && is_convertible<typename ExecutionContext::executor_type,
  360. AwaitableExecutor>::value
  361. >)
  362. {
  363. return (co_spawn)(ctx.get_executor(), std::move(a),
  364. std::forward<CompletionToken>(token));
  365. }
  366. template <typename Executor, typename F,
  367. BOOST_ASIO_COMPLETION_TOKEN_FOR(typename detail::awaitable_signature<
  368. result_of_t<F()>>::type) CompletionToken>
  369. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken,
  370. typename detail::awaitable_signature<result_of_t<F()>>::type)
  371. co_spawn(const Executor& ex, F&& f, CompletionToken&& token,
  372. constraint_t<
  373. is_executor<Executor>::value || execution::is_executor<Executor>::value
  374. >)
  375. {
  376. return async_initiate<CompletionToken,
  377. typename detail::awaitable_signature<result_of_t<F()>>::type>(
  378. detail::initiate_co_spawn<
  379. typename result_of_t<F()>::executor_type>(ex),
  380. token, std::forward<F>(f));
  381. }
  382. template <typename ExecutionContext, typename F,
  383. BOOST_ASIO_COMPLETION_TOKEN_FOR(typename detail::awaitable_signature<
  384. result_of_t<F()>>::type) CompletionToken>
  385. inline BOOST_ASIO_INITFN_AUTO_RESULT_TYPE(CompletionToken,
  386. typename detail::awaitable_signature<result_of_t<F()>>::type)
  387. co_spawn(ExecutionContext& ctx, F&& f, CompletionToken&& token,
  388. constraint_t<
  389. is_convertible<ExecutionContext&, execution_context&>::value
  390. >)
  391. {
  392. return (co_spawn)(ctx.get_executor(), std::forward<F>(f),
  393. std::forward<CompletionToken>(token));
  394. }
  395. } // namespace asio
  396. } // namespace boost
  397. #include <boost/asio/detail/pop_options.hpp>
  398. #endif // BOOST_ASIO_IMPL_CO_SPAWN_HPP