thread.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. // SPDX-FileCopyrightText: 2013 Dolphin Emulator Project
  2. // SPDX-FileCopyrightText: 2014 Citra Emulator Project
  3. // SPDX-License-Identifier: GPL-2.0-or-later
  4. #pragma once
  5. #include <atomic>
  6. #include <chrono>
  7. #include <condition_variable>
  8. #include <cstddef>
  9. #include <mutex>
  10. #include <thread>
  11. #include "common/common_types.h"
  12. namespace Common {
  13. class Event {
  14. public:
  15. void Set() {
  16. std::scoped_lock lk{mutex};
  17. if (!is_set) {
  18. is_set = true;
  19. condvar.notify_one();
  20. }
  21. }
  22. void Wait() {
  23. std::unique_lock lk{mutex};
  24. condvar.wait(lk, [&] { return is_set.load(); });
  25. is_set = false;
  26. }
  27. bool WaitFor(const std::chrono::nanoseconds& time) {
  28. std::unique_lock lk{mutex};
  29. if (!condvar.wait_for(lk, time, [this] { return is_set.load(); }))
  30. return false;
  31. is_set = false;
  32. return true;
  33. }
  34. template <class Clock, class Duration>
  35. bool WaitUntil(const std::chrono::time_point<Clock, Duration>& time) {
  36. std::unique_lock lk{mutex};
  37. if (!condvar.wait_until(lk, time, [this] { return is_set.load(); }))
  38. return false;
  39. is_set = false;
  40. return true;
  41. }
  42. void Reset() {
  43. std::unique_lock lk{mutex};
  44. // no other action required, since wait loops on the predicate and any lingering signal will
  45. // get cleared on the first iteration
  46. is_set = false;
  47. }
  48. [[nodiscard]] bool IsSet() {
  49. return is_set;
  50. }
  51. private:
  52. std::condition_variable condvar;
  53. std::mutex mutex;
  54. std::atomic_bool is_set{false};
  55. };
  56. class Barrier {
  57. public:
  58. explicit Barrier(std::size_t count_) : count(count_) {}
  59. /// Blocks until all "count" threads have called Sync()
  60. void Sync() {
  61. std::unique_lock lk{mutex};
  62. const std::size_t current_generation = generation;
  63. if (++waiting == count) {
  64. generation++;
  65. waiting = 0;
  66. condvar.notify_all();
  67. } else {
  68. condvar.wait(lk,
  69. [this, current_generation] { return current_generation != generation; });
  70. }
  71. }
  72. private:
  73. std::condition_variable condvar;
  74. std::mutex mutex;
  75. std::size_t count;
  76. std::size_t waiting = 0;
  77. std::size_t generation = 0; // Incremented once each time the barrier is used
  78. };
  79. enum class ThreadPriority : u32 {
  80. Low = 0,
  81. Normal = 1,
  82. High = 2,
  83. VeryHigh = 3,
  84. Critical = 4,
  85. };
  86. void SetCurrentThreadPriority(ThreadPriority new_priority);
  87. void SetCurrentThreadName(const char* name);
  88. } // namespace Common