thread.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright 2013 Dolphin Emulator Project / 2014 Citra Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  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::lock_guard 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. private:
  49. std::condition_variable condvar;
  50. std::mutex mutex;
  51. std::atomic_bool is_set{false};
  52. };
  53. class Barrier {
  54. public:
  55. explicit Barrier(std::size_t count_) : count(count_) {}
  56. /// Blocks until all "count" threads have called Sync()
  57. void Sync() {
  58. std::unique_lock lk{mutex};
  59. const std::size_t current_generation = generation;
  60. if (++waiting == count) {
  61. generation++;
  62. waiting = 0;
  63. condvar.notify_all();
  64. } else {
  65. condvar.wait(lk,
  66. [this, current_generation] { return current_generation != generation; });
  67. }
  68. }
  69. private:
  70. std::condition_variable condvar;
  71. std::mutex mutex;
  72. std::size_t count;
  73. std::size_t waiting = 0;
  74. std::size_t generation = 0; // Incremented once each time the barrier is used
  75. };
  76. enum class ThreadPriority : u32 {
  77. Low = 0,
  78. Normal = 1,
  79. High = 2,
  80. VeryHigh = 3,
  81. };
  82. void SetCurrentThreadPriority(ThreadPriority new_priority);
  83. void SetCurrentThreadName(const char* name);
  84. } // namespace Common