thread.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. namespace Common {
  11. class Event {
  12. public:
  13. void Set() {
  14. std::lock_guard lk{mutex};
  15. if (!is_set) {
  16. is_set = true;
  17. condvar.notify_one();
  18. }
  19. }
  20. void Wait() {
  21. std::unique_lock lk{mutex};
  22. condvar.wait(lk, [&] { return is_set; });
  23. is_set = false;
  24. }
  25. template <class Duration>
  26. bool WaitFor(const std::chrono::duration<Duration>& 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. void SetCurrentThreadName(const char* name);
  76. } // namespace Common