thread.hpp 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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_THREAD_HPP
  8. #define BOOST_COBALT_DETAIL_THREAD_HPP
  9. #include <boost/cobalt/config.hpp>
  10. #include <boost/cobalt/detail/forward_cancellation.hpp>
  11. #include <boost/cobalt/detail/handler.hpp>
  12. #include <boost/cobalt/concepts.hpp>
  13. #include <boost/cobalt/this_coro.hpp>
  14. #include <boost/asio/cancellation_signal.hpp>
  15. #include <thread>
  16. namespace boost::cobalt
  17. {
  18. struct as_tuple_tag;
  19. struct as_result_tag;
  20. namespace detail
  21. {
  22. struct thread_promise;
  23. }
  24. struct thread;
  25. namespace detail
  26. {
  27. struct signal_helper_2
  28. {
  29. asio::cancellation_signal signal;
  30. };
  31. struct thread_state
  32. {
  33. asio::io_context ctx{1u};
  34. asio::cancellation_signal signal;
  35. std::mutex mtx;
  36. std::optional<completion_handler<std::exception_ptr>> waitor;
  37. std::atomic<bool> done = false;
  38. };
  39. struct thread_promise : signal_helper_2,
  40. promise_cancellation_base<asio::cancellation_slot, asio::enable_total_cancellation>,
  41. promise_throw_if_cancelled_base,
  42. enable_awaitables<thread_promise>,
  43. enable_await_allocator<thread_promise>,
  44. enable_await_executor<thread_promise>
  45. {
  46. BOOST_COBALT_DECL thread_promise();
  47. struct initial_awaitable
  48. {
  49. bool await_ready() const {return false;}
  50. void await_suspend(std::coroutine_handle<thread_promise> h)
  51. {
  52. h.promise().mtx.unlock();
  53. }
  54. void await_resume() {}
  55. };
  56. auto initial_suspend() noexcept
  57. {
  58. return initial_awaitable{};
  59. }
  60. std::suspend_never final_suspend() noexcept
  61. {
  62. wexec_.reset();
  63. return {};
  64. }
  65. void unhandled_exception() { throw; }
  66. void return_void() { }
  67. using executor_type = typename cobalt::executor;
  68. const executor_type & get_executor() const {return *exec_;}
  69. #if !defined(BOOST_COBALT_NO_PMR)
  70. using allocator_type = pmr::polymorphic_allocator<void>;
  71. using resource_type = pmr::unsynchronized_pool_resource;
  72. resource_type * resource;
  73. allocator_type get_allocator() const { return allocator_type(resource); }
  74. #endif
  75. using promise_cancellation_base<asio::cancellation_slot, asio::enable_total_cancellation>::await_transform;
  76. using promise_throw_if_cancelled_base::await_transform;
  77. using enable_awaitables<thread_promise>::await_transform;
  78. using enable_await_allocator<thread_promise>::await_transform;
  79. using enable_await_executor<thread_promise>::await_transform;
  80. BOOST_COBALT_DECL
  81. boost::cobalt::thread get_return_object();
  82. void set_executor(asio::io_context::executor_type exec)
  83. {
  84. wexec_.emplace(exec);
  85. exec_.emplace(exec);
  86. }
  87. std::mutex mtx;
  88. private:
  89. std::optional<asio::executor_work_guard<asio::io_context::executor_type>> wexec_;
  90. std::optional<cobalt::executor> exec_;
  91. };
  92. struct thread_awaitable
  93. {
  94. asio::cancellation_slot cl;
  95. std::optional<std::tuple<std::exception_ptr>> res;
  96. bool await_ready(const boost::source_location & loc = BOOST_CURRENT_LOCATION) const
  97. {
  98. if (state_ == nullptr)
  99. boost::throw_exception(std::invalid_argument("Thread expired"), loc);
  100. std::lock_guard<std::mutex> lock{state_->mtx};
  101. return state_->done;
  102. }
  103. template<typename Promise>
  104. bool await_suspend(std::coroutine_handle<Promise> h)
  105. {
  106. BOOST_ASSERT(state_);
  107. std::lock_guard<std::mutex> lock{state_->mtx};
  108. if (state_->done)
  109. return false;
  110. if constexpr (requires (Promise p) {p.get_cancellation_slot();})
  111. if ((cl = h.promise().get_cancellation_slot()).is_connected())
  112. {
  113. cl.assign(
  114. [st = state_](asio::cancellation_type type)
  115. {
  116. std::lock_guard<std::mutex> lock{st->mtx};
  117. asio::post(st->ctx,
  118. [st, type]
  119. {
  120. BOOST_ASIO_HANDLER_LOCATION((__FILE__, __LINE__, __func__));
  121. st->signal.emit(type);
  122. });
  123. });
  124. }
  125. state_->waitor.emplace(h, res);
  126. return true;
  127. }
  128. void await_resume()
  129. {
  130. if (cl.is_connected())
  131. cl.clear();
  132. if (thread_)
  133. thread_->join();
  134. if (!res) // await_ready
  135. return;
  136. if (auto ee = std::get<0>(*res))
  137. std::rethrow_exception(ee);
  138. }
  139. system::result<void, std::exception_ptr> await_resume(const as_result_tag &)
  140. {
  141. if (cl.is_connected())
  142. cl.clear();
  143. if (thread_)
  144. thread_->join();
  145. if (!res) // await_ready
  146. return {system::in_place_value};
  147. if (auto ee = std::get<0>(*res))
  148. return {system::in_place_error, std::move(ee)};
  149. return {system::in_place_value};
  150. }
  151. std::tuple<std::exception_ptr> await_resume(const as_tuple_tag &)
  152. {
  153. if (cl.is_connected())
  154. cl.clear();
  155. if (thread_)
  156. thread_->join();
  157. return std::get<0>(*res);
  158. }
  159. explicit thread_awaitable(std::shared_ptr<detail::thread_state> state)
  160. : state_(std::move(state)) {}
  161. explicit thread_awaitable(std::thread thread,
  162. std::shared_ptr<detail::thread_state> state)
  163. : thread_(std::move(thread)), state_(std::move(state)) {}
  164. private:
  165. std::optional<std::thread> thread_;
  166. std::shared_ptr<detail::thread_state> state_;
  167. };
  168. }
  169. }
  170. #endif //BOOST_COBALT_DETAIL_THREAD_HPP