co_spawn.hpp 13 KB

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