join.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. //
  2. // Copyright (c) 2022 Klemens Morgenstern (klemens.morgenstern@gmx.net)
  3. //
  4. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. #ifndef BOOST_COBALT_DETAIL_JOIN_HPP
  8. #define BOOST_COBALT_DETAIL_JOIN_HPP
  9. #include <boost/cobalt/detail/await_result_helper.hpp>
  10. #include <boost/cobalt/detail/exception.hpp>
  11. #include <boost/cobalt/detail/fork.hpp>
  12. #include <boost/cobalt/detail/forward_cancellation.hpp>
  13. #include <boost/cobalt/detail/util.hpp>
  14. #include <boost/cobalt/detail/wrapper.hpp>
  15. #include <boost/cobalt/task.hpp>
  16. #include <boost/cobalt/this_thread.hpp>
  17. #include <boost/asio/associated_cancellation_slot.hpp>
  18. #include <boost/asio/bind_cancellation_slot.hpp>
  19. #include <boost/asio/cancellation_signal.hpp>
  20. #include <boost/core/ignore_unused.hpp>
  21. #include <boost/intrusive_ptr.hpp>
  22. #include <boost/system/result.hpp>
  23. #include <boost/variant2/variant.hpp>
  24. #include <array>
  25. #include <coroutine>
  26. #include <algorithm>
  27. namespace boost::cobalt::detail
  28. {
  29. template<typename ... Args>
  30. struct join_variadic_impl
  31. {
  32. using tuple_type = std::tuple<decltype(get_awaitable_type(std::declval<Args&&>()))...>;
  33. join_variadic_impl(Args && ... args)
  34. : args{std::forward<Args>(args)...}
  35. {
  36. }
  37. std::tuple<Args...> args;
  38. constexpr static std::size_t tuple_size = sizeof...(Args);
  39. struct awaitable : fork::static_shared_state<256 * tuple_size>
  40. {
  41. template<std::size_t ... Idx>
  42. awaitable(std::tuple<Args...> & args, std::index_sequence<Idx...>) :
  43. aws(awaitable_type_getter<Args>(std::get<Idx>(args))...)
  44. {
  45. }
  46. tuple_type aws;
  47. std::array<asio::cancellation_signal, tuple_size> cancel_;
  48. template<typename > constexpr static auto make_null() {return nullptr;};
  49. std::array<asio::cancellation_signal*, tuple_size> cancel = {make_null<Args>()...};
  50. constexpr static bool all_void = (std::is_void_v<co_await_result_t<Args>> && ...);
  51. template<typename T>
  52. using result_store_part =
  53. std::optional<void_as_monostate<co_await_result_t<T>>>;
  54. std::conditional_t<all_void,
  55. variant2::monostate,
  56. std::tuple<result_store_part<Args>...>> result;
  57. std::exception_ptr error;
  58. template<std::size_t Idx>
  59. void cancel_step()
  60. {
  61. auto &r = cancel[Idx];
  62. if (r)
  63. std::exchange(r, nullptr)->emit(asio::cancellation_type::all);
  64. }
  65. void cancel_all()
  66. {
  67. mp11::mp_for_each<mp11::mp_iota_c<sizeof...(Args)>>
  68. ([&](auto idx)
  69. {
  70. cancel_step<idx>();
  71. });
  72. }
  73. template<std::size_t Idx>
  74. void interrupt_await_step()
  75. {
  76. using type = std::tuple_element_t<Idx, tuple_type>;
  77. using t = std::conditional_t<std::is_reference_v<std::tuple_element_t<Idx, std::tuple<Args...>>>,
  78. type &,
  79. type &&>;
  80. if constexpr (interruptible<t>)
  81. if (this->cancel[Idx] != nullptr)
  82. static_cast<t>(std::get<Idx>(aws)).interrupt_await();
  83. }
  84. void interrupt_await()
  85. {
  86. mp11::mp_for_each<mp11::mp_iota_c<sizeof...(Args)>>
  87. ([&](auto idx)
  88. {
  89. interrupt_await_step<idx>();
  90. });
  91. }
  92. // GCC doesn't like member funs
  93. template<std::size_t Idx>
  94. static detail::fork await_impl(awaitable & this_)
  95. BOOST_TRY
  96. {
  97. auto & aw = std::get<Idx>(this_.aws);
  98. // check manually if we're ready
  99. auto rd = aw.await_ready();
  100. if (!rd)
  101. {
  102. this_.cancel[Idx] = &this_.cancel_[Idx];
  103. co_await this_.cancel[Idx]->slot();
  104. // make sure the executor is set
  105. co_await detail::fork::wired_up;
  106. // do the await - this doesn't call await-ready again
  107. if constexpr (std::is_void_v<decltype(aw.await_resume())>)
  108. {
  109. co_await aw;
  110. if constexpr (!all_void)
  111. std::get<Idx>(this_.result).emplace();
  112. }
  113. else
  114. std::get<Idx>(this_.result).emplace(co_await aw);
  115. }
  116. else
  117. {
  118. if constexpr (std::is_void_v<decltype(aw.await_resume())>)
  119. {
  120. aw.await_resume();
  121. if constexpr (!all_void)
  122. std::get<Idx>(this_.result).emplace();
  123. }
  124. else
  125. std::get<Idx>(this_.result).emplace(aw.await_resume());
  126. }
  127. }
  128. BOOST_CATCH(...)
  129. {
  130. if (!this_.error)
  131. this_.error = std::current_exception();
  132. this_.cancel_all();
  133. }
  134. BOOST_CATCH_END
  135. std::array<detail::fork(*)(awaitable&), tuple_size> impls {
  136. []<std::size_t ... Idx>(std::index_sequence<Idx...>)
  137. {
  138. return std::array<detail::fork(*)(awaitable&), tuple_size>{&await_impl<Idx>...};
  139. }(std::make_index_sequence<tuple_size>{})
  140. };
  141. detail::fork last_forked;
  142. std::size_t last_index = 0u;
  143. bool await_ready()
  144. {
  145. while (last_index < tuple_size)
  146. {
  147. last_forked = impls[last_index++](*this);
  148. if (!last_forked.done())
  149. return false; // one coro didn't immediately complete!
  150. }
  151. last_forked.release();
  152. return true;
  153. }
  154. template<typename H>
  155. auto await_suspend(
  156. std::coroutine_handle<H> h
  157. #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING)
  158. , const boost::source_location & loc = BOOST_CURRENT_LOCATION
  159. #endif
  160. )
  161. {
  162. #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING)
  163. this->loc = loc;
  164. #endif
  165. this->exec = &detail::get_executor(h);
  166. last_forked.release().resume();
  167. while (last_index < tuple_size)
  168. impls[last_index++](*this).release();
  169. if (error)
  170. cancel_all();
  171. if (!this->outstanding_work()) // already done, resume rightaway.
  172. return false;
  173. // arm the cancel
  174. assign_cancellation(
  175. h,
  176. [&](asio::cancellation_type ct)
  177. {
  178. for (auto cs : cancel)
  179. if (cs)
  180. cs->emit(ct);
  181. });
  182. this->coro.reset(h.address());
  183. return true;
  184. }
  185. #if _MSC_VER
  186. BOOST_NOINLINE
  187. #endif
  188. auto await_resume()
  189. {
  190. if (error)
  191. std::rethrow_exception(error);
  192. if constexpr(!all_void)
  193. return mp11::tuple_transform(
  194. []<typename T>(std::optional<T> & var)
  195. -> T
  196. {
  197. BOOST_ASSERT(var.has_value());
  198. return std::move(*var);
  199. }, result);
  200. }
  201. auto await_resume(const as_tuple_tag &)
  202. {
  203. using t = decltype(await_resume());
  204. if constexpr(!all_void)
  205. {
  206. if (error)
  207. return std::make_tuple(error, t{});
  208. else
  209. return std::make_tuple(std::current_exception(),
  210. mp11::tuple_transform(
  211. []<typename T>(std::optional<T> & var)
  212. -> T
  213. {
  214. BOOST_ASSERT(var.has_value());
  215. return std::move(*var);
  216. }, result));
  217. }
  218. else
  219. return std::make_tuple(error);
  220. }
  221. auto await_resume(const as_result_tag &)
  222. {
  223. using t = decltype(await_resume());
  224. using rt = system::result<t, std::exception_ptr>;
  225. if (error)
  226. return rt(system::in_place_error, error);
  227. if constexpr(!all_void)
  228. return mp11::tuple_transform(
  229. []<typename T>(std::optional<T> & var)
  230. -> rt
  231. {
  232. BOOST_ASSERT(var.has_value());
  233. return std::move(*var);
  234. }, result);
  235. else
  236. return rt{system::in_place_value};
  237. }
  238. };
  239. awaitable operator co_await() &&
  240. {
  241. return awaitable(args, std::make_index_sequence<sizeof...(Args)>{});
  242. }
  243. };
  244. template<typename Range>
  245. struct join_ranged_impl
  246. {
  247. Range aws;
  248. using result_type = co_await_result_t<std::decay_t<decltype(*std::begin(std::declval<Range>()))>>;
  249. constexpr static std::size_t result_size =
  250. sizeof(std::conditional_t<std::is_void_v<result_type>, variant2::monostate, result_type>);
  251. struct awaitable : fork::shared_state
  252. {
  253. struct dummy
  254. {
  255. template<typename ... Args>
  256. dummy(Args && ...) {}
  257. };
  258. using type = std::decay_t<decltype(*std::begin(std::declval<Range>()))>;
  259. #if !defined(BOOST_COBALT_NO_PMR)
  260. pmr::polymorphic_allocator<void> alloc{&resource};
  261. std::conditional_t<awaitable_type<type>, Range &,
  262. pmr::vector<co_awaitable_type<type>>> aws;
  263. pmr::vector<bool> ready{std::size(aws), alloc};
  264. pmr::vector<asio::cancellation_signal> cancel_{std::size(aws), alloc};
  265. pmr::vector<asio::cancellation_signal*> cancel{std::size(aws), alloc};
  266. std::conditional_t<
  267. std::is_void_v<result_type>,
  268. dummy,
  269. pmr::vector<std::optional<void_as_monostate<result_type>>>>
  270. result{
  271. cancel.size(),
  272. alloc};
  273. #else
  274. std::allocator<void> alloc;
  275. std::conditional_t<awaitable_type<type>, Range &, std::vector<co_awaitable_type<type>>> aws;
  276. std::vector<bool> ready{std::size(aws), alloc};
  277. std::vector<asio::cancellation_signal> cancel_{std::size(aws), alloc};
  278. std::vector<asio::cancellation_signal*> cancel{std::size(aws), alloc};
  279. std::conditional_t<
  280. std::is_void_v<result_type>,
  281. dummy,
  282. std::vector<std::optional<void_as_monostate<result_type>>>>
  283. result{
  284. cancel.size(),
  285. alloc};
  286. #endif
  287. std::exception_ptr error;
  288. awaitable(Range & aws_, std::false_type /* needs operator co_await */)
  289. : fork::shared_state((512 + sizeof(co_awaitable_type<type>) + result_size) * std::size(aws_))
  290. , aws{alloc}
  291. , ready{std::size(aws_), alloc}
  292. , cancel_{std::size(aws_), alloc}
  293. , cancel{std::size(aws_), alloc}
  294. {
  295. aws.reserve(std::size(aws_));
  296. for (auto && a : aws_)
  297. {
  298. using a_0 = std::decay_t<decltype(a)>;
  299. using a_t = std::conditional_t<
  300. std::is_lvalue_reference_v<Range>, a_0 &, a_0 &&>;
  301. aws.emplace_back(awaitable_type_getter<a_t>(static_cast<a_t>(a)));
  302. }
  303. std::transform(std::begin(this->aws),
  304. std::end(this->aws),
  305. std::begin(ready),
  306. [](auto & aw) {return aw.await_ready();});
  307. }
  308. awaitable(Range & aws, std::true_type /* needs operator co_await */)
  309. : fork::shared_state((512 + sizeof(co_awaitable_type<type>) + result_size) * std::size(aws))
  310. , aws(aws)
  311. {
  312. std::transform(std::begin(aws), std::end(aws), std::begin(ready), [](auto & aw) {return aw.await_ready();});
  313. }
  314. awaitable(Range & aws)
  315. : awaitable(aws, std::bool_constant<awaitable_type<type>>{})
  316. {
  317. }
  318. void cancel_all()
  319. {
  320. for (auto & r : cancel)
  321. if (r)
  322. std::exchange(r, nullptr)->emit(asio::cancellation_type::all);
  323. }
  324. void interrupt_await()
  325. {
  326. using t = std::conditional_t<std::is_reference_v<Range>,
  327. co_awaitable_type<type> &,
  328. co_awaitable_type<type> &&>;
  329. if constexpr (interruptible<t>)
  330. {
  331. std::size_t idx = 0u;
  332. for (auto & aw : aws)
  333. if (cancel[idx])
  334. static_cast<t>(aw).interrupt_await();
  335. }
  336. }
  337. static detail::fork await_impl(awaitable & this_, std::size_t idx)
  338. BOOST_TRY
  339. {
  340. auto & aw = *std::next(std::begin(this_.aws), idx);
  341. auto rd = aw.await_ready();
  342. if (!rd)
  343. {
  344. this_.cancel[idx] = &this_.cancel_[idx];
  345. co_await this_.cancel[idx]->slot();
  346. co_await detail::fork::wired_up;
  347. if constexpr (std::is_void_v<decltype(aw.await_resume())>)
  348. co_await aw;
  349. else
  350. this_.result[idx].emplace(co_await aw);
  351. }
  352. else
  353. {
  354. if constexpr (std::is_void_v<decltype(aw.await_resume())>)
  355. aw.await_resume();
  356. else
  357. this_.result[idx].emplace(aw.await_resume());
  358. }
  359. }
  360. BOOST_CATCH(...)
  361. {
  362. if (!this_.error)
  363. this_.error = std::current_exception();
  364. this_.cancel_all();
  365. }
  366. BOOST_CATCH_END
  367. detail::fork last_forked;
  368. std::size_t last_index = 0u;
  369. bool await_ready()
  370. {
  371. while (last_index < cancel.size())
  372. {
  373. last_forked = await_impl(*this, last_index++);
  374. if (!last_forked.done())
  375. return false; // one coro didn't immediately complete!
  376. }
  377. last_forked.release();
  378. return true;
  379. }
  380. template<typename H>
  381. auto await_suspend(
  382. std::coroutine_handle<H> h
  383. #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING)
  384. , const boost::source_location & loc = BOOST_CURRENT_LOCATION
  385. #endif
  386. )
  387. {
  388. #if defined(BOOST_ASIO_ENABLE_HANDLER_TRACKING)
  389. this->loc = loc;
  390. #endif
  391. exec = &detail::get_executor(h);
  392. last_forked.release().resume();
  393. while (last_index < cancel.size())
  394. await_impl(*this, last_index++).release();
  395. if (error)
  396. cancel_all();
  397. if (!this->outstanding_work()) // already done, resume right away.
  398. return false;
  399. // arm the cancel
  400. assign_cancellation(
  401. h,
  402. [&](asio::cancellation_type ct)
  403. {
  404. for (auto cs : cancel)
  405. if (cs)
  406. cs->emit(ct);
  407. });
  408. this->coro.reset(h.address());
  409. return true;
  410. }
  411. auto await_resume(const as_tuple_tag & )
  412. {
  413. #if defined(BOOST_COBALT_NO_PMR)
  414. std::vector<result_type> rr;
  415. #else
  416. pmr::vector<result_type> rr{this_thread::get_allocator()};
  417. #endif
  418. if (error)
  419. return std::make_tuple(error, rr);
  420. if constexpr (!std::is_void_v<result_type>)
  421. {
  422. rr.reserve(result.size());
  423. for (auto & t : result)
  424. rr.push_back(*std::move(t));
  425. return std::make_tuple(std::exception_ptr(), std::move(rr));
  426. }
  427. }
  428. auto await_resume(const as_result_tag & )
  429. {
  430. #if defined(BOOST_COBALT_NO_PMR)
  431. std::vector<result_type> rr;
  432. #else
  433. pmr::vector<result_type> rr{this_thread::get_allocator()};
  434. #endif
  435. if (error)
  436. return system::result<decltype(rr), std::exception_ptr>(error);
  437. if constexpr (!std::is_void_v<result_type>)
  438. {
  439. rr.reserve(result.size());
  440. for (auto & t : result)
  441. rr.push_back(*std::move(t));
  442. return rr;
  443. }
  444. }
  445. #if _MSC_VER
  446. BOOST_NOINLINE
  447. #endif
  448. auto await_resume()
  449. {
  450. if (error)
  451. std::rethrow_exception(error);
  452. if constexpr (!std::is_void_v<result_type>)
  453. {
  454. #if defined(BOOST_COBALT_NO_PMR)
  455. std::vector<result_type> rr;
  456. #else
  457. pmr::vector<result_type> rr{this_thread::get_allocator()};
  458. #endif
  459. rr.reserve(result.size());
  460. for (auto & t : result)
  461. rr.push_back(*std::move(t));
  462. return rr;
  463. }
  464. }
  465. };
  466. awaitable operator co_await() && {return awaitable{aws};}
  467. };
  468. }
  469. #endif //BOOST_COBALT_DETAIL_JOIN_HPP