parallel_group.hpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. //
  2. // experimental/parallel_group.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_EXPERIMENTAL_PARALLEL_GROUP_HPP
  11. #define BOOST_ASIO_EXPERIMENTAL_PARALLEL_GROUP_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 <vector>
  17. #include <boost/asio/async_result.hpp>
  18. #include <boost/asio/detail/array.hpp>
  19. #include <boost/asio/detail/memory.hpp>
  20. #include <boost/asio/detail/throw_exception.hpp>
  21. #include <boost/asio/detail/type_traits.hpp>
  22. #include <boost/asio/detail/utility.hpp>
  23. #include <boost/asio/experimental/cancellation_condition.hpp>
  24. #include <boost/asio/detail/push_options.hpp>
  25. namespace boost {
  26. namespace asio {
  27. namespace experimental {
  28. namespace detail {
  29. // Helper trait for getting a tuple from a completion signature.
  30. template <typename Signature>
  31. struct parallel_op_signature_as_tuple;
  32. template <typename R, typename... Args>
  33. struct parallel_op_signature_as_tuple<R(Args...)>
  34. {
  35. typedef std::tuple<decay_t<Args>...> type;
  36. };
  37. // Helper trait for concatenating completion signatures.
  38. template <std::size_t N, typename Offsets, typename... Signatures>
  39. struct parallel_group_signature;
  40. template <std::size_t N, typename R0, typename... Args0>
  41. struct parallel_group_signature<N, R0(Args0...)>
  42. {
  43. typedef boost::asio::detail::array<std::size_t, N> order_type;
  44. typedef R0 raw_type(Args0...);
  45. typedef R0 type(order_type, Args0...);
  46. };
  47. template <std::size_t N,
  48. typename R0, typename... Args0,
  49. typename R1, typename... Args1>
  50. struct parallel_group_signature<N, R0(Args0...), R1(Args1...)>
  51. {
  52. typedef boost::asio::detail::array<std::size_t, N> order_type;
  53. typedef R0 raw_type(Args0..., Args1...);
  54. typedef R0 type(order_type, Args0..., Args1...);
  55. };
  56. template <std::size_t N, typename Sig0,
  57. typename Sig1, typename... SigN>
  58. struct parallel_group_signature<N, Sig0, Sig1, SigN...>
  59. {
  60. typedef boost::asio::detail::array<std::size_t, N> order_type;
  61. typedef typename parallel_group_signature<N,
  62. typename parallel_group_signature<N, Sig0, Sig1>::raw_type,
  63. SigN...>::raw_type raw_type;
  64. typedef typename parallel_group_signature<N,
  65. typename parallel_group_signature<N, Sig0, Sig1>::raw_type,
  66. SigN...>::type type;
  67. };
  68. template <typename Condition, typename Handler,
  69. typename... Ops, std::size_t... I>
  70. void parallel_group_launch(Condition cancellation_condition, Handler handler,
  71. std::tuple<Ops...>& ops, boost::asio::detail::index_sequence<I...>);
  72. // Helper trait for determining ranged parallel group completion signatures.
  73. template <typename Signature, typename Allocator>
  74. struct ranged_parallel_group_signature;
  75. template <typename R, typename... Args, typename Allocator>
  76. struct ranged_parallel_group_signature<R(Args...), Allocator>
  77. {
  78. typedef std::vector<std::size_t,
  79. BOOST_ASIO_REBIND_ALLOC(Allocator, std::size_t)> order_type;
  80. typedef R raw_type(
  81. std::vector<Args, BOOST_ASIO_REBIND_ALLOC(Allocator, Args)>...);
  82. typedef R type(order_type,
  83. std::vector<Args, BOOST_ASIO_REBIND_ALLOC(Allocator, Args)>...);
  84. };
  85. template <typename Condition, typename Handler,
  86. typename Range, typename Allocator>
  87. void ranged_parallel_group_launch(Condition cancellation_condition,
  88. Handler handler, Range&& range, const Allocator& allocator);
  89. char (&parallel_group_has_iterator_helper(...))[2];
  90. template <typename T>
  91. char parallel_group_has_iterator_helper(T*, typename T::iterator* = 0);
  92. template <typename T>
  93. struct parallel_group_has_iterator_typedef
  94. {
  95. enum { value = (sizeof((parallel_group_has_iterator_helper)((T*)(0))) == 1) };
  96. };
  97. } // namespace detail
  98. /// Type trait used to determine whether a type is a range of asynchronous
  99. /// operations that can be used with with @c make_parallel_group.
  100. template <typename T>
  101. struct is_async_operation_range
  102. {
  103. #if defined(GENERATING_DOCUMENTATION)
  104. /// The value member is true if the type may be used as a range of
  105. /// asynchronous operations.
  106. static const bool value;
  107. #else
  108. enum
  109. {
  110. value = detail::parallel_group_has_iterator_typedef<T>::value
  111. };
  112. #endif
  113. };
  114. /// A group of asynchronous operations that may be launched in parallel.
  115. /**
  116. * See the documentation for boost::asio::experimental::make_parallel_group for
  117. * a usage example.
  118. */
  119. template <typename... Ops>
  120. class parallel_group
  121. {
  122. private:
  123. struct initiate_async_wait
  124. {
  125. template <typename Handler, typename Condition>
  126. void operator()(Handler&& h, Condition&& c, std::tuple<Ops...>&& ops) const
  127. {
  128. detail::parallel_group_launch(
  129. std::forward<Condition>(c), std::forward<Handler>(h),
  130. ops, boost::asio::detail::index_sequence_for<Ops...>());
  131. }
  132. };
  133. std::tuple<Ops...> ops_;
  134. public:
  135. static_assert(sizeof...(Ops) >= 1,
  136. "parallel_group requires at least one operation");
  137. /// Constructor.
  138. explicit parallel_group(Ops... ops)
  139. : ops_(std::move(ops)...)
  140. {
  141. }
  142. /// The completion signature for the group of operations.
  143. typedef typename detail::parallel_group_signature<sizeof...(Ops),
  144. completion_signature_of_t<Ops>...>::type signature;
  145. /// Initiate an asynchronous wait for the group of operations.
  146. /**
  147. * Launches the group and asynchronously waits for completion.
  148. *
  149. * @param cancellation_condition A function object, called on completion of
  150. * an operation within the group, that is used to determine whether to cancel
  151. * the remaining operations. The function object is passed the arguments of
  152. * the completed operation's handler. To trigger cancellation of the remaining
  153. * operations, it must return a boost::asio::cancellation_type value other
  154. * than <tt>boost::asio::cancellation_type::none</tt>.
  155. *
  156. * @param token A @ref completion_token whose signature is comprised of
  157. * a @c std::array<std::size_t, N> indicating the completion order of the
  158. * operations, followed by all operations' completion handler arguments.
  159. *
  160. * The library provides the following @c cancellation_condition types:
  161. *
  162. * @li boost::asio::experimental::wait_for_all
  163. * @li boost::asio::experimental::wait_for_one
  164. * @li boost::asio::experimental::wait_for_one_error
  165. * @li boost::asio::experimental::wait_for_one_success
  166. */
  167. template <typename CancellationCondition,
  168. BOOST_ASIO_COMPLETION_TOKEN_FOR(signature) CompletionToken>
  169. auto async_wait(CancellationCondition cancellation_condition,
  170. CompletionToken&& token)
  171. -> decltype(
  172. boost::asio::async_initiate<CompletionToken, signature>(
  173. declval<initiate_async_wait>(), token,
  174. std::move(cancellation_condition), std::move(ops_)))
  175. {
  176. return boost::asio::async_initiate<CompletionToken, signature>(
  177. initiate_async_wait(), token,
  178. std::move(cancellation_condition), std::move(ops_));
  179. }
  180. };
  181. /// Create a group of operations that may be launched in parallel.
  182. /**
  183. * For example:
  184. * @code boost::asio::experimental::make_parallel_group(
  185. * in.async_read_some(boost::asio::buffer(data)),
  186. * timer.async_wait()
  187. * ).async_wait(
  188. * boost::asio::experimental::wait_for_all(),
  189. * [](
  190. * std::array<std::size_t, 2> completion_order,
  191. * boost::system::error_code ec1, std::size_t n1,
  192. * boost::system::error_code ec2
  193. * )
  194. * {
  195. * switch (completion_order[0])
  196. * {
  197. * case 0:
  198. * {
  199. * std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n";
  200. * }
  201. * break;
  202. * case 1:
  203. * {
  204. * std::cout << "timer finished: " << ec2 << "\n";
  205. * }
  206. * break;
  207. * }
  208. * }
  209. * );
  210. * @endcode
  211. *
  212. * If preferred, the asynchronous operations may be explicitly packaged as
  213. * function objects:
  214. * @code boost::asio::experimental::make_parallel_group(
  215. * [&](auto token)
  216. * {
  217. * return in.async_read_some(boost::asio::buffer(data), token);
  218. * },
  219. * [&](auto token)
  220. * {
  221. * return timer.async_wait(token);
  222. * }
  223. * ).async_wait(
  224. * boost::asio::experimental::wait_for_all(),
  225. * [](
  226. * std::array<std::size_t, 2> completion_order,
  227. * boost::system::error_code ec1, std::size_t n1,
  228. * boost::system::error_code ec2
  229. * )
  230. * {
  231. * switch (completion_order[0])
  232. * {
  233. * case 0:
  234. * {
  235. * std::cout << "descriptor finished: " << ec1 << ", " << n1 << "\n";
  236. * }
  237. * break;
  238. * case 1:
  239. * {
  240. * std::cout << "timer finished: " << ec2 << "\n";
  241. * }
  242. * break;
  243. * }
  244. * }
  245. * );
  246. * @endcode
  247. */
  248. template <typename... Ops>
  249. BOOST_ASIO_NODISCARD inline parallel_group<Ops...>
  250. make_parallel_group(Ops... ops)
  251. {
  252. return parallel_group<Ops...>(std::move(ops)...);
  253. }
  254. /// A range-based group of asynchronous operations that may be launched in
  255. /// parallel.
  256. /**
  257. * See the documentation for boost::asio::experimental::make_parallel_group for
  258. * a usage example.
  259. */
  260. template <typename Range, typename Allocator = std::allocator<void>>
  261. class ranged_parallel_group
  262. {
  263. private:
  264. struct initiate_async_wait
  265. {
  266. template <typename Handler, typename Condition>
  267. void operator()(Handler&& h, Condition&& c,
  268. Range&& range, const Allocator& allocator) const
  269. {
  270. detail::ranged_parallel_group_launch(std::move(c),
  271. std::move(h), std::forward<Range>(range), allocator);
  272. }
  273. };
  274. Range range_;
  275. Allocator allocator_;
  276. public:
  277. /// Constructor.
  278. /**
  279. * @throws std::logic_error Thrown if the range is empty.
  280. */
  281. explicit ranged_parallel_group(Range range,
  282. const Allocator& allocator = Allocator())
  283. : range_(std::move(range)),
  284. allocator_(allocator)
  285. {
  286. if (range_.empty())
  287. {
  288. std::logic_error e("ranged_parallel_group must be non-empty");
  289. boost::asio::detail::throw_exception(e);
  290. }
  291. }
  292. /// The completion signature for the group of operations.
  293. typedef typename detail::ranged_parallel_group_signature<
  294. completion_signature_of_t<
  295. decay_t<decltype(*std::declval<typename Range::iterator>())>>,
  296. Allocator>::type signature;
  297. /// Initiate an asynchronous wait for the group of operations.
  298. /**
  299. * Launches the group and asynchronously waits for completion.
  300. *
  301. * @param cancellation_condition A function object, called on completion of
  302. * an operation within the group, that is used to determine whether to cancel
  303. * the remaining operations. The function object is passed the arguments of
  304. * the completed operation's handler. To trigger cancellation of the remaining
  305. * operations, it must return a boost::asio::cancellation_type value other
  306. * than <tt>boost::asio::cancellation_type::none</tt>.
  307. *
  308. * @param token A @ref completion_token whose signature is comprised of
  309. * a @c std::vector<std::size_t, Allocator> indicating the completion order of
  310. * the operations, followed by a vector for each of the completion signature's
  311. * arguments.
  312. *
  313. * The library provides the following @c cancellation_condition types:
  314. *
  315. * @li boost::asio::experimental::wait_for_all
  316. * @li boost::asio::experimental::wait_for_one
  317. * @li boost::asio::experimental::wait_for_one_error
  318. * @li boost::asio::experimental::wait_for_one_success
  319. */
  320. template <typename CancellationCondition,
  321. BOOST_ASIO_COMPLETION_TOKEN_FOR(signature) CompletionToken>
  322. auto async_wait(CancellationCondition cancellation_condition,
  323. CompletionToken&& token)
  324. -> decltype(
  325. boost::asio::async_initiate<CompletionToken, signature>(
  326. declval<initiate_async_wait>(), token,
  327. std::move(cancellation_condition),
  328. std::move(range_), allocator_))
  329. {
  330. return boost::asio::async_initiate<CompletionToken, signature>(
  331. initiate_async_wait(), token,
  332. std::move(cancellation_condition),
  333. std::move(range_), allocator_);
  334. }
  335. };
  336. /// Create a group of operations that may be launched in parallel.
  337. /**
  338. * @param range A range containing the operations to be launched.
  339. *
  340. * @throws std::logic_error Thrown if the range is empty.
  341. *
  342. * For example:
  343. * @code
  344. * using op_type =
  345. * decltype(socket1.async_read_some(boost::asio::buffer(data1)));
  346. *
  347. * std::vector<op_type> ops;
  348. * ops.push_back(socket1.async_read_some(boost::asio::buffer(data1)));
  349. * ops.push_back(socket2.async_read_some(boost::asio::buffer(data2)));
  350. *
  351. * boost::asio::experimental::make_parallel_group(ops).async_wait(
  352. * boost::asio::experimental::wait_for_all(),
  353. * [](
  354. * std::vector<std::size_t> completion_order,
  355. * std::vector<boost::system::error_code> e,
  356. * std::vector<std::size_t> n
  357. * )
  358. * {
  359. * for (std::size_t i = 0; i < completion_order.size(); ++i)
  360. * {
  361. * std::size_t idx = completion_order[i];
  362. * std::cout << "socket " << idx << " finished: ";
  363. * std::cout << e[idx] << ", " << n[idx] << "\n";
  364. * }
  365. * }
  366. * );
  367. * @endcode
  368. */
  369. template <typename Range>
  370. BOOST_ASIO_NODISCARD inline ranged_parallel_group<decay_t<Range>>
  371. make_parallel_group(Range&& range,
  372. constraint_t<
  373. is_async_operation_range<decay_t<Range>>::value
  374. > = 0)
  375. {
  376. return ranged_parallel_group<decay_t<Range>>(std::forward<Range>(range));
  377. }
  378. /// Create a group of operations that may be launched in parallel.
  379. /**
  380. * @param allocator Specifies the allocator to be used with the result vectors.
  381. *
  382. * @param range A range containing the operations to be launched.
  383. *
  384. * @throws std::logic_error Thrown if the range is empty.
  385. *
  386. * For example:
  387. * @code
  388. * using op_type =
  389. * decltype(socket1.async_read_some(boost::asio::buffer(data1)));
  390. *
  391. * std::vector<op_type> ops;
  392. * ops.push_back(socket1.async_read_some(boost::asio::buffer(data1)));
  393. * ops.push_back(socket2.async_read_some(boost::asio::buffer(data2)));
  394. *
  395. * boost::asio::experimental::make_parallel_group(
  396. * std::allocator_arg_t,
  397. * my_allocator,
  398. * ops
  399. * ).async_wait(
  400. * boost::asio::experimental::wait_for_all(),
  401. * [](
  402. * std::vector<std::size_t> completion_order,
  403. * std::vector<boost::system::error_code> e,
  404. * std::vector<std::size_t> n
  405. * )
  406. * {
  407. * for (std::size_t i = 0; i < completion_order.size(); ++i)
  408. * {
  409. * std::size_t idx = completion_order[i];
  410. * std::cout << "socket " << idx << " finished: ";
  411. * std::cout << e[idx] << ", " << n[idx] << "\n";
  412. * }
  413. * }
  414. * );
  415. * @endcode
  416. */
  417. template <typename Allocator, typename Range>
  418. BOOST_ASIO_NODISCARD inline ranged_parallel_group<decay_t<Range>, Allocator>
  419. make_parallel_group(allocator_arg_t, const Allocator& allocator, Range&& range,
  420. constraint_t<
  421. is_async_operation_range<decay_t<Range>>::value
  422. > = 0)
  423. {
  424. return ranged_parallel_group<decay_t<Range>, Allocator>(
  425. std::forward<Range>(range), allocator);
  426. }
  427. } // namespace experimental
  428. } // namespace asio
  429. } // namespace boost
  430. #include <boost/asio/detail/pop_options.hpp>
  431. #include <boost/asio/experimental/impl/parallel_group.hpp>
  432. #endif // BOOST_ASIO_EXPERIMENTAL_PARALLEL_GROUP_HPP