polyfill_thread.h 9.9 KB

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