async_mutex.hpp 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. //
  2. // Copyright (c) 2023-2025 Ivica Siladic, Bruno Iljazovic, Korina Simicevic
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. //
  7. #ifndef BOOST_MQTT5_ASYNC_MUTEX_HPP
  8. #define BOOST_MQTT5_ASYNC_MUTEX_HPP
  9. #include <boost/mqtt5/detail/async_traits.hpp>
  10. #include <boost/asio/any_completion_handler.hpp>
  11. #include <boost/asio/any_io_executor.hpp>
  12. #include <boost/asio/associated_allocator.hpp>
  13. #include <boost/asio/associated_cancellation_slot.hpp>
  14. #include <boost/asio/async_result.hpp>
  15. #include <boost/asio/bind_cancellation_slot.hpp>
  16. #include <boost/asio/execution.hpp>
  17. #include <boost/asio/require.hpp>
  18. #include <boost/system/error_code.hpp>
  19. #include <deque>
  20. namespace boost::mqtt5::detail {
  21. namespace asio = boost::asio;
  22. using error_code = boost::system::error_code;
  23. class async_mutex {
  24. public:
  25. using executor_type = asio::any_io_executor;
  26. private:
  27. using queued_op_t = asio::any_completion_handler<
  28. void (error_code)
  29. >;
  30. using queue_t = std::deque<queued_op_t>;
  31. // Handler with assigned tracking executor.
  32. // Objects of this type are type-erased by any_completion_handler
  33. // and stored in the waiting queue.
  34. template <typename Handler, typename Executor>
  35. class tracked_op {
  36. tracking_type<Handler, Executor> _executor;
  37. Handler _handler;
  38. public:
  39. tracked_op(Handler&& h, const Executor& ex) :
  40. _executor(tracking_executor(h, ex)), _handler(std::move(h))
  41. {}
  42. tracked_op(tracked_op&&) = default;
  43. tracked_op(const tracked_op&) = delete;
  44. tracked_op& operator=(tracked_op&&) = default;
  45. tracked_op& operator=(const tracked_op&) = delete;
  46. using allocator_type = asio::associated_allocator_t<Handler>;
  47. allocator_type get_allocator() const noexcept {
  48. return asio::get_associated_allocator(_handler);
  49. }
  50. using cancellation_slot_type =
  51. asio::associated_cancellation_slot_t<Handler>;
  52. cancellation_slot_type get_cancellation_slot() const noexcept {
  53. return asio::get_associated_cancellation_slot(_handler);
  54. }
  55. using executor_type = tracking_type<Handler, Executor>;
  56. executor_type get_executor() const noexcept {
  57. return _executor;
  58. }
  59. void operator()(error_code ec) {
  60. std::move(_handler)(ec);
  61. }
  62. };
  63. // Per-operation cancellation helper.
  64. // It is safe to emit the cancellation signal from any thread
  65. // provided there are no other concurrent calls to the async_mutex.
  66. // The helper stores queue iterator to operation since the iterator
  67. // would not be invalidated by other queue operations.
  68. class cancel_waiting_op {
  69. queue_t::iterator _ihandler;
  70. public:
  71. explicit cancel_waiting_op(queue_t::iterator ih) : _ihandler(ih) {}
  72. void operator()(asio::cancellation_type_t type) {
  73. if (type == asio::cancellation_type_t::none)
  74. return;
  75. if (*_ihandler) {
  76. auto h = std::move(*_ihandler);
  77. auto ex = asio::get_associated_executor(h);
  78. asio::require(ex, asio::execution::blocking.possibly)
  79. .execute([h = std::move(h)]() mutable {
  80. std::move(h)(asio::error::operation_aborted);
  81. });
  82. }
  83. }
  84. };
  85. bool _locked { false };
  86. queue_t _waiting;
  87. executor_type _ex;
  88. public:
  89. template <typename Executor>
  90. explicit async_mutex(Executor&& ex) : _ex(std::forward<Executor>(ex)) {}
  91. async_mutex(const async_mutex&) = delete;
  92. async_mutex& operator=(const async_mutex&) = delete;
  93. ~async_mutex() {
  94. cancel();
  95. }
  96. const executor_type& get_executor() const noexcept {
  97. return _ex;
  98. }
  99. bool is_locked() const noexcept {
  100. return _locked;
  101. }
  102. // Schedules mutex for lock operation and return immediately.
  103. // Calls given completion handler when mutex is locked.
  104. // It's the responsibility of the completion handler to unlock the mutex.
  105. template <typename CompletionToken>
  106. decltype(auto) lock(CompletionToken&& token) noexcept {
  107. using Signature = void (error_code);
  108. auto initiation = [] (auto handler, async_mutex& self) {
  109. self.execute_or_queue(std::move(handler));
  110. };
  111. return asio::async_initiate<CompletionToken, Signature>(
  112. initiation, token, std::ref(*this)
  113. );
  114. }
  115. // Unlocks the mutex. The mutex must be in locked state.
  116. // Next queued operation, if any, will be executed in a manner
  117. // equivalent to asio::post.
  118. void unlock() {
  119. while (!_waiting.empty()) {
  120. auto op = std::move(_waiting.front());
  121. _waiting.pop_front();
  122. if (!op) continue;
  123. op.get_cancellation_slot().clear();
  124. execute_op(std::move(op));
  125. return;
  126. }
  127. _locked = false;
  128. }
  129. // Cancels all outstanding operations waiting on the mutex.
  130. void cancel() {
  131. while (!_waiting.empty()) {
  132. auto op = std::move(_waiting.front());
  133. _waiting.pop_front();
  134. if (!op) continue;
  135. op.get_cancellation_slot().clear();
  136. asio::require(_ex, asio::execution::blocking.never)
  137. .execute([ex = _ex, op = std::move(op)]() mutable {
  138. auto opex = asio::get_associated_executor(op, ex);
  139. opex.execute(
  140. [op = std::move(op)]() mutable {
  141. op(asio::error::operation_aborted);
  142. }
  143. );
  144. });
  145. }
  146. }
  147. private:
  148. // Schedule operation to `opex` executor using `_ex` executor.
  149. // The operation is equivalent to asio::post(_ex, op) but
  150. // for some reason this form of execution is much faster.
  151. void execute_op(queued_op_t op) {
  152. asio::require(_ex, asio::execution::blocking.never)
  153. .execute([ex = _ex, op = std::move(op)]() mutable {
  154. auto opex = asio::get_associated_executor(op, ex);
  155. opex.execute(
  156. [op = std::move(op)]() mutable {
  157. op(error_code {});
  158. }
  159. );
  160. });
  161. }
  162. // Executes operation immediately if mutex is not locked
  163. // or queues it for later execution otherwise. In both cases
  164. // the operation will be executed in a manner equivalent
  165. // to asio::post to avoid recursion.
  166. template <typename Handler>
  167. void execute_or_queue(Handler&& handler) noexcept {
  168. tracked_op h { std::move(handler), _ex };
  169. if (_locked) {
  170. _waiting.emplace_back(std::move(h));
  171. auto slot = _waiting.back().get_cancellation_slot();
  172. if (slot.is_connected())
  173. slot.template emplace<cancel_waiting_op>(
  174. _waiting.end() - 1
  175. );
  176. }
  177. else {
  178. _locked = true;
  179. execute_op(queued_op_t { std::move(h) });
  180. }
  181. }
  182. };
  183. } // end namespace boost::mqtt5::detail
  184. #endif // !BOOST_MQTT5_ASYNC_MUTEX_HPP