polyfill_thread.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // SPDX-FileCopyrightText: 2022 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. //
  4. // TODO: remove this file when jthread is supported by all compilation targets
  5. //
  6. #pragma once
  7. #include <version>
  8. #ifdef __cpp_lib_jthread
  9. #include <chrono>
  10. #include <condition_variable>
  11. #include <stop_token>
  12. #include <thread>
  13. namespace Common {
  14. template <typename Condvar, typename Lock, typename Pred>
  15. void CondvarWait(Condvar& cv, Lock& lock, std::stop_token token, Pred&& pred) {
  16. cv.wait(lock, token, std::move(pred));
  17. }
  18. template <typename Rep, typename Period>
  19. bool StoppableTimedWait(std::stop_token token, const std::chrono::duration<Rep, Period>& rel_time) {
  20. std::condition_variable_any cv;
  21. std::mutex m;
  22. // Perform the timed wait.
  23. std::unique_lock lk{m};
  24. return !cv.wait_for(lk, token, rel_time, [&] { return token.stop_requested(); });
  25. }
  26. } // namespace Common
  27. #else
  28. #include <atomic>
  29. #include <chrono>
  30. #include <condition_variable>
  31. #include <functional>
  32. #include <map>
  33. #include <memory>
  34. #include <mutex>
  35. #include <optional>
  36. #include <thread>
  37. #include <type_traits>
  38. #include <utility>
  39. namespace std {
  40. namespace polyfill {
  41. using stop_state_callback = size_t;
  42. class stop_state {
  43. public:
  44. stop_state() = default;
  45. ~stop_state() = default;
  46. bool request_stop() {
  47. unique_lock lk{m_lock};
  48. if (m_stop_requested) {
  49. // Already set, nothing to do.
  50. return false;
  51. }
  52. // Mark stop requested.
  53. m_stop_requested = true;
  54. while (!m_callbacks.empty()) {
  55. // Get an iterator to the first element.
  56. const auto it = m_callbacks.begin();
  57. // Move the callback function out of the map.
  58. function<void()> f;
  59. swap(it->second, f);
  60. // Erase the now-empty map element.
  61. m_callbacks.erase(it);
  62. // Run the callback.
  63. if (f) {
  64. f();
  65. }
  66. }
  67. return true;
  68. }
  69. bool stop_requested() const {
  70. unique_lock lk{m_lock};
  71. return m_stop_requested;
  72. }
  73. stop_state_callback insert_callback(function<void()> f) {
  74. unique_lock lk{m_lock};
  75. if (m_stop_requested) {
  76. // Stop already requested. Don't insert anything,
  77. // just run the callback synchronously.
  78. if (f) {
  79. f();
  80. }
  81. return 0;
  82. }
  83. // Insert the callback.
  84. stop_state_callback ret = ++m_next_callback;
  85. m_callbacks.emplace(ret, move(f));
  86. return ret;
  87. }
  88. void remove_callback(stop_state_callback cb) {
  89. unique_lock lk{m_lock};
  90. m_callbacks.erase(cb);
  91. }
  92. private:
  93. mutable recursive_mutex m_lock;
  94. map<stop_state_callback, function<void()>> m_callbacks;
  95. stop_state_callback m_next_callback{0};
  96. bool m_stop_requested{false};
  97. };
  98. } // namespace polyfill
  99. class stop_token;
  100. class stop_source;
  101. struct nostopstate_t {
  102. explicit nostopstate_t() = default;
  103. };
  104. inline constexpr nostopstate_t nostopstate{};
  105. template <class Callback>
  106. class stop_callback;
  107. class stop_token {
  108. public:
  109. stop_token() noexcept = default;
  110. stop_token(const stop_token&) noexcept = default;
  111. stop_token(stop_token&&) noexcept = default;
  112. stop_token& operator=(const stop_token&) noexcept = default;
  113. stop_token& operator=(stop_token&&) noexcept = default;
  114. ~stop_token() = default;
  115. void swap(stop_token& other) noexcept {
  116. m_stop_state.swap(other.m_stop_state);
  117. }
  118. [[nodiscard]] bool stop_requested() const noexcept {
  119. return m_stop_state && m_stop_state->stop_requested();
  120. }
  121. [[nodiscard]] bool stop_possible() const noexcept {
  122. return m_stop_state != nullptr;
  123. }
  124. private:
  125. friend class stop_source;
  126. template <typename Callback>
  127. friend class stop_callback;
  128. stop_token(shared_ptr<polyfill::stop_state> stop_state) : m_stop_state(move(stop_state)) {}
  129. private:
  130. shared_ptr<polyfill::stop_state> m_stop_state;
  131. };
  132. class stop_source {
  133. public:
  134. stop_source() : m_stop_state(make_shared<polyfill::stop_state>()) {}
  135. explicit stop_source(nostopstate_t) noexcept {}
  136. stop_source(const stop_source&) noexcept = default;
  137. stop_source(stop_source&&) noexcept = default;
  138. stop_source& operator=(const stop_source&) noexcept = default;
  139. stop_source& operator=(stop_source&&) noexcept = default;
  140. ~stop_source() = default;
  141. void swap(stop_source& other) noexcept {
  142. m_stop_state.swap(other.m_stop_state);
  143. }
  144. [[nodiscard]] stop_token get_token() const noexcept {
  145. return stop_token(m_stop_state);
  146. }
  147. [[nodiscard]] bool stop_possible() const noexcept {
  148. return m_stop_state != nullptr;
  149. }
  150. [[nodiscard]] bool stop_requested() const noexcept {
  151. return m_stop_state && m_stop_state->stop_requested();
  152. }
  153. bool request_stop() noexcept {
  154. return m_stop_state && m_stop_state->request_stop();
  155. }
  156. private:
  157. friend class jthread;
  158. explicit stop_source(shared_ptr<polyfill::stop_state> stop_state)
  159. : m_stop_state(move(stop_state)) {}
  160. private:
  161. shared_ptr<polyfill::stop_state> m_stop_state;
  162. };
  163. template <typename Callback>
  164. class stop_callback {
  165. static_assert(is_nothrow_destructible_v<Callback>);
  166. static_assert(is_invocable_v<Callback>);
  167. public:
  168. using callback_type = Callback;
  169. template <typename C>
  170. requires constructible_from<Callback, C>
  171. explicit stop_callback(const stop_token& st,
  172. C&& cb) noexcept(is_nothrow_constructible_v<Callback, C>)
  173. : m_stop_state(st.m_stop_state) {
  174. if (m_stop_state) {
  175. m_callback = m_stop_state->insert_callback(move(cb));
  176. }
  177. }
  178. template <typename C>
  179. requires constructible_from<Callback, C>
  180. explicit stop_callback(stop_token&& st,
  181. C&& cb) noexcept(is_nothrow_constructible_v<Callback, C>)
  182. : m_stop_state(move(st.m_stop_state)) {
  183. if (m_stop_state) {
  184. m_callback = m_stop_state->insert_callback(move(cb));
  185. }
  186. }
  187. ~stop_callback() {
  188. if (m_stop_state && m_callback) {
  189. m_stop_state->remove_callback(m_callback);
  190. }
  191. }
  192. stop_callback(const stop_callback&) = delete;
  193. stop_callback(stop_callback&&) = delete;
  194. stop_callback& operator=(const stop_callback&) = delete;
  195. stop_callback& operator=(stop_callback&&) = delete;
  196. private:
  197. shared_ptr<polyfill::stop_state> m_stop_state;
  198. polyfill::stop_state_callback m_callback;
  199. };
  200. template <typename Callback>
  201. stop_callback(stop_token, Callback) -> stop_callback<Callback>;
  202. class jthread {
  203. public:
  204. using id = thread::id;
  205. using native_handle_type = thread::native_handle_type;
  206. jthread() noexcept = default;
  207. template <typename F, typename... Args,
  208. typename = enable_if_t<!is_same_v<remove_cvref_t<F>, jthread>>>
  209. explicit jthread(F&& f, Args&&... args)
  210. : m_stop_state(make_shared<polyfill::stop_state>()),
  211. m_thread(make_thread(move(f), move(args)...)) {}
  212. ~jthread() {
  213. if (joinable()) {
  214. request_stop();
  215. join();
  216. }
  217. }
  218. jthread(const jthread&) = delete;
  219. jthread(jthread&&) noexcept = default;
  220. jthread& operator=(const jthread&) = delete;
  221. jthread& operator=(jthread&& other) noexcept {
  222. m_thread.swap(other.m_thread);
  223. m_stop_state.swap(other.m_stop_state);
  224. return *this;
  225. }
  226. void swap(jthread& other) noexcept {
  227. m_thread.swap(other.m_thread);
  228. m_stop_state.swap(other.m_stop_state);
  229. }
  230. [[nodiscard]] bool joinable() const noexcept {
  231. return m_thread.joinable();
  232. }
  233. void join() {
  234. m_thread.join();
  235. }
  236. void detach() {
  237. m_thread.detach();
  238. m_stop_state.reset();
  239. }
  240. [[nodiscard]] id get_id() const noexcept {
  241. return m_thread.get_id();
  242. }
  243. [[nodiscard]] native_handle_type native_handle() {
  244. return m_thread.native_handle();
  245. }
  246. [[nodiscard]] stop_source get_stop_source() noexcept {
  247. return stop_source(m_stop_state);
  248. }
  249. [[nodiscard]] stop_token get_stop_token() const noexcept {
  250. return stop_source(m_stop_state).get_token();
  251. }
  252. bool request_stop() noexcept {
  253. return get_stop_source().request_stop();
  254. }
  255. [[nodiscard]] static unsigned int hardware_concurrency() noexcept {
  256. return thread::hardware_concurrency();
  257. }
  258. private:
  259. template <typename F, typename... Args>
  260. thread make_thread(F&& f, Args&&... args) {
  261. if constexpr (is_invocable_v<decay_t<F>, stop_token, decay_t<Args>...>) {
  262. return thread(move(f), get_stop_token(), move(args)...);
  263. } else {
  264. return thread(move(f), move(args)...);
  265. }
  266. }
  267. shared_ptr<polyfill::stop_state> m_stop_state;
  268. thread m_thread;
  269. };
  270. } // namespace std
  271. namespace Common {
  272. template <typename Condvar, typename Lock, typename Pred>
  273. void CondvarWait(Condvar& cv, Lock& lock, std::stop_token token, Pred pred) {
  274. if (token.stop_requested()) {
  275. return;
  276. }
  277. std::stop_callback callback(token, [&] { cv.notify_all(); });
  278. cv.wait(lock, [&] { return pred() || token.stop_requested(); });
  279. }
  280. template <typename Rep, typename Period>
  281. bool StoppableTimedWait(std::stop_token token, const std::chrono::duration<Rep, Period>& rel_time) {
  282. if (token.stop_requested()) {
  283. return false;
  284. }
  285. bool stop_requested = false;
  286. std::condition_variable cv;
  287. std::mutex m;
  288. std::stop_callback cb(token, [&] {
  289. // Wake up the waiting thread.
  290. std::unique_lock lk{m};
  291. stop_requested = true;
  292. cv.notify_one();
  293. });
  294. // Perform the timed wait.
  295. std::unique_lock lk{m};
  296. return !cv.wait_for(lk, rel_time, [&] { return stop_requested; });
  297. }
  298. } // namespace Common
  299. #endif