thread.h 2.4 KB

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