basic_channel.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. //
  2. // experimental/basic_channel.hpp
  3. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. //
  5. // Copyright (c) 2003-2022 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 ASIO_EXPERIMENTAL_BASIC_CHANNEL_HPP
  11. #define ASIO_EXPERIMENTAL_BASIC_CHANNEL_HPP
  12. #if defined(_MSC_VER) && (_MSC_VER >= 1200)
  13. # pragma once
  14. #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
  15. #include "asio/detail/config.hpp"
  16. #include "asio/detail/non_const_lvalue.hpp"
  17. #include "asio/detail/null_mutex.hpp"
  18. #include "asio/execution/executor.hpp"
  19. #include "asio/execution_context.hpp"
  20. #include "asio/experimental/detail/channel_send_functions.hpp"
  21. #include "asio/experimental/detail/channel_service.hpp"
  22. #include "asio/detail/push_options.hpp"
  23. namespace asio {
  24. namespace experimental {
  25. namespace detail {
  26. } // namespace detail
  27. /// A channel for messages.
  28. template <typename Executor, typename Traits, typename... Signatures>
  29. class basic_channel
  30. #if !defined(GENERATING_DOCUMENTATION)
  31. : public detail::channel_send_functions<
  32. basic_channel<Executor, Traits, Signatures...>,
  33. Executor, Signatures...>
  34. #endif // !defined(GENERATING_DOCUMENTATION)
  35. {
  36. private:
  37. class initiate_async_send;
  38. class initiate_async_receive;
  39. typedef detail::channel_service<asio::detail::null_mutex> service_type;
  40. typedef typename service_type::template implementation_type<
  41. Traits, Signatures...>::payload_type payload_type;
  42. template <typename... PayloadSignatures,
  43. ASIO_COMPLETION_TOKEN_FOR(PayloadSignatures...) CompletionToken>
  44. auto do_async_receive(detail::channel_payload<PayloadSignatures...>*,
  45. ASIO_MOVE_ARG(CompletionToken) token)
  46. -> decltype(
  47. async_initiate<CompletionToken, PayloadSignatures...>(
  48. declval<initiate_async_receive>(), token))
  49. {
  50. return async_initiate<CompletionToken, PayloadSignatures...>(
  51. initiate_async_receive(this), token);
  52. }
  53. public:
  54. /// The type of the executor associated with the channel.
  55. typedef Executor executor_type;
  56. /// Rebinds the channel type to another executor.
  57. template <typename Executor1>
  58. struct rebind_executor
  59. {
  60. /// The channel type when rebound to the specified executor.
  61. typedef basic_channel<Executor1, Traits, Signatures...> other;
  62. };
  63. /// The traits type associated with the channel.
  64. typedef typename Traits::template rebind<Signatures...>::other traits_type;
  65. /// Construct a basic_channel.
  66. /**
  67. * This constructor creates and channel.
  68. *
  69. * @param ex The I/O executor that the channel will use, by default, to
  70. * dispatch handlers for any asynchronous operations performed on the channel.
  71. *
  72. * @param max_buffer_size The maximum number of messages that may be buffered
  73. * in the channel.
  74. */
  75. basic_channel(const executor_type& ex, std::size_t max_buffer_size = 0)
  76. : service_(&asio::use_service<service_type>(
  77. basic_channel::get_context(ex))),
  78. impl_(),
  79. executor_(ex)
  80. {
  81. service_->construct(impl_, max_buffer_size);
  82. }
  83. /// Construct and open a basic_channel.
  84. /**
  85. * This constructor creates and opens a channel.
  86. *
  87. * @param context An execution context which provides the I/O executor that
  88. * the channel will use, by default, to dispatch handlers for any asynchronous
  89. * operations performed on the channel.
  90. *
  91. * @param max_buffer_size The maximum number of messages that may be buffered
  92. * in the channel.
  93. */
  94. template <typename ExecutionContext>
  95. basic_channel(ExecutionContext& context, std::size_t max_buffer_size = 0,
  96. typename constraint<
  97. is_convertible<ExecutionContext&, execution_context&>::value,
  98. defaulted_constraint
  99. >::type = defaulted_constraint())
  100. : service_(&asio::use_service<service_type>(context)),
  101. impl_(),
  102. executor_(context.get_executor())
  103. {
  104. service_->construct(impl_, max_buffer_size);
  105. }
  106. #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  107. /// Move-construct a basic_channel from another.
  108. /**
  109. * This constructor moves a channel from one object to another.
  110. *
  111. * @param other The other basic_channel object from which the move will occur.
  112. *
  113. * @note Following the move, the moved-from object is in the same state as if
  114. * constructed using the @c basic_channel(const executor_type&) constructor.
  115. */
  116. basic_channel(basic_channel&& other)
  117. : service_(other.service_),
  118. executor_(other.executor_)
  119. {
  120. service_->move_construct(impl_, other.impl_);
  121. }
  122. /// Move-assign a basic_channel from another.
  123. /**
  124. * This assignment operator moves a channel from one object to another.
  125. * Cancels any outstanding asynchronous operations associated with the target
  126. * object.
  127. *
  128. * @param other The other basic_channel object from which the move will occur.
  129. *
  130. * @note Following the move, the moved-from object is in the same state as if
  131. * constructed using the @c basic_channel(const executor_type&)
  132. * constructor.
  133. */
  134. basic_channel& operator=(basic_channel&& other)
  135. {
  136. if (this != &other)
  137. {
  138. service_->move_assign(impl_, *other.service_, other.impl_);
  139. executor_.~executor_type();
  140. new (&executor_) executor_type(other.executor_);
  141. service_ = other.service_;
  142. }
  143. return *this;
  144. }
  145. // All channels have access to each other's implementations.
  146. template <typename, typename, typename...>
  147. friend class basic_channel;
  148. /// Move-construct a basic_channel from another.
  149. /**
  150. * This constructor moves a channel from one object to another.
  151. *
  152. * @param other The other basic_channel object from which the move will occur.
  153. *
  154. * @note Following the move, the moved-from object is in the same state as if
  155. * constructed using the @c basic_channel(const executor_type&)
  156. * constructor.
  157. */
  158. template <typename Executor1>
  159. basic_channel(
  160. basic_channel<Executor1, Traits, Signatures...>&& other,
  161. typename constraint<
  162. is_convertible<Executor1, Executor>::value
  163. >::type = 0)
  164. : service_(other.service_),
  165. executor_(other.executor_)
  166. {
  167. service_->move_construct(impl_, *other.service_, other.impl_);
  168. }
  169. /// Move-assign a basic_channel from another.
  170. /**
  171. * This assignment operator moves a channel from one object to another.
  172. * Cancels any outstanding asynchronous operations associated with the target
  173. * object.
  174. *
  175. * @param other The other basic_channel object from which the move will
  176. * occur.
  177. *
  178. * @note Following the move, the moved-from object is in the same state as if
  179. * constructed using the @c basic_channel(const executor_type&)
  180. * constructor.
  181. */
  182. template <typename Executor1>
  183. typename constraint<
  184. is_convertible<Executor1, Executor>::value,
  185. basic_channel&
  186. >::type operator=(basic_channel<Executor1, Traits, Signatures...>&& other)
  187. {
  188. if (this != &other)
  189. {
  190. service_->move_assign(impl_, *other.service_, other.impl_);
  191. executor_.~executor_type();
  192. new (&executor_) executor_type(other.executor_);
  193. service_ = other.service_;
  194. }
  195. return *this;
  196. }
  197. #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION)
  198. /// Destructor.
  199. ~basic_channel()
  200. {
  201. service_->destroy(impl_);
  202. }
  203. /// Get the executor associated with the object.
  204. executor_type get_executor() ASIO_NOEXCEPT
  205. {
  206. return executor_;
  207. }
  208. /// Get the capacity of the channel's buffer.
  209. std::size_t capacity() ASIO_NOEXCEPT
  210. {
  211. return service_->capacity(impl_);
  212. }
  213. /// Determine whether the channel is open.
  214. bool is_open() const ASIO_NOEXCEPT
  215. {
  216. return service_->is_open(impl_);
  217. }
  218. /// Reset the channel to its initial state.
  219. void reset()
  220. {
  221. service_->reset(impl_);
  222. }
  223. /// Close the channel.
  224. void close()
  225. {
  226. service_->close(impl_);
  227. }
  228. /// Cancel all asynchronous operations waiting on the channel.
  229. /**
  230. * All outstanding send operations will complete with the error
  231. * @c asio::experimental::error::channel_canceld. Outstanding receive
  232. * operations complete with the result as determined by the channel traits.
  233. */
  234. void cancel()
  235. {
  236. service_->cancel(impl_);
  237. }
  238. /// Determine whether a message can be received without blocking.
  239. bool ready() const ASIO_NOEXCEPT
  240. {
  241. return service_->ready(impl_);
  242. }
  243. #if defined(GENERATING_DOCUMENTATION)
  244. /// Try to send a message without blocking.
  245. /**
  246. * Fails if the buffer is full and there are no waiting receive operations.
  247. *
  248. * @returns @c true on success, @c false on failure.
  249. */
  250. template <typename... Args>
  251. bool try_send(ASIO_MOVE_ARG(Args)... args);
  252. /// Try to send a number of messages without blocking.
  253. /**
  254. * @returns The number of messages that were sent.
  255. */
  256. template <typename... Args>
  257. std::size_t try_send_n(std::size_t count, ASIO_MOVE_ARG(Args)... args);
  258. /// Asynchronously send a message.
  259. /**
  260. * @par Completion Signature
  261. * @code void(asio::error_code) @endcode
  262. */
  263. template <typename... Args,
  264. ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code))
  265. CompletionToken ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
  266. auto async_send(ASIO_MOVE_ARG(Args)... args,
  267. ASIO_MOVE_ARG(CompletionToken) token);
  268. #endif // defined(GENERATING_DOCUMENTATION)
  269. /// Try to receive a message without blocking.
  270. /**
  271. * Fails if the buffer is full and there are no waiting receive operations.
  272. *
  273. * @returns @c true on success, @c false on failure.
  274. */
  275. template <typename Handler>
  276. bool try_receive(ASIO_MOVE_ARG(Handler) handler)
  277. {
  278. return service_->try_receive(impl_, ASIO_MOVE_CAST(Handler)(handler));
  279. }
  280. /// Asynchronously receive a message.
  281. /**
  282. * @par Completion Signature
  283. * As determined by the <tt>Signatures...</tt> template parameter and the
  284. * channel traits.
  285. */
  286. template <typename CompletionToken
  287. ASIO_DEFAULT_COMPLETION_TOKEN_TYPE(executor_type)>
  288. auto async_receive(
  289. ASIO_MOVE_ARG(CompletionToken) token
  290. ASIO_DEFAULT_COMPLETION_TOKEN(Executor))
  291. #if !defined(GENERATING_DOCUMENTATION)
  292. -> decltype(
  293. this->do_async_receive(static_cast<payload_type*>(0),
  294. ASIO_MOVE_CAST(CompletionToken)(token)))
  295. #endif // !defined(GENERATING_DOCUMENTATION)
  296. {
  297. return this->do_async_receive(static_cast<payload_type*>(0),
  298. ASIO_MOVE_CAST(CompletionToken)(token));
  299. }
  300. private:
  301. // Disallow copying and assignment.
  302. basic_channel(const basic_channel&) ASIO_DELETED;
  303. basic_channel& operator=(const basic_channel&) ASIO_DELETED;
  304. template <typename, typename, typename...>
  305. friend class detail::channel_send_functions;
  306. // Helper function to get an executor's context.
  307. template <typename T>
  308. static execution_context& get_context(const T& t,
  309. typename enable_if<execution::is_executor<T>::value>::type* = 0)
  310. {
  311. return asio::query(t, execution::context);
  312. }
  313. // Helper function to get an executor's context.
  314. template <typename T>
  315. static execution_context& get_context(const T& t,
  316. typename enable_if<!execution::is_executor<T>::value>::type* = 0)
  317. {
  318. return t.context();
  319. }
  320. class initiate_async_send
  321. {
  322. public:
  323. typedef Executor executor_type;
  324. explicit initiate_async_send(basic_channel* self)
  325. : self_(self)
  326. {
  327. }
  328. executor_type get_executor() const ASIO_NOEXCEPT
  329. {
  330. return self_->get_executor();
  331. }
  332. template <typename SendHandler>
  333. void operator()(ASIO_MOVE_ARG(SendHandler) handler,
  334. ASIO_MOVE_ARG(payload_type) payload) const
  335. {
  336. asio::detail::non_const_lvalue<SendHandler> handler2(handler);
  337. self_->service_->async_send(self_->impl_,
  338. ASIO_MOVE_CAST(payload_type)(payload),
  339. handler2.value, self_->get_executor());
  340. }
  341. private:
  342. basic_channel* self_;
  343. };
  344. class initiate_async_receive
  345. {
  346. public:
  347. typedef Executor executor_type;
  348. explicit initiate_async_receive(basic_channel* self)
  349. : self_(self)
  350. {
  351. }
  352. executor_type get_executor() const ASIO_NOEXCEPT
  353. {
  354. return self_->get_executor();
  355. }
  356. template <typename ReceiveHandler>
  357. void operator()(ASIO_MOVE_ARG(ReceiveHandler) handler) const
  358. {
  359. asio::detail::non_const_lvalue<ReceiveHandler> handler2(handler);
  360. self_->service_->async_receive(self_->impl_,
  361. handler2.value, self_->get_executor());
  362. }
  363. private:
  364. basic_channel* self_;
  365. };
  366. // The service associated with the I/O object.
  367. service_type* service_;
  368. // The underlying implementation of the I/O object.
  369. typename service_type::template implementation_type<
  370. Traits, Signatures...> impl_;
  371. // The associated executor.
  372. Executor executor_;
  373. };
  374. } // namespace experimental
  375. } // namespace asio
  376. #include "asio/detail/pop_options.hpp"
  377. #endif // ASIO_EXPERIMENTAL_BASIC_CHANNEL_HPP