thread.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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<std::mutex> lk(mutex);
  16. if (!is_set) {
  17. is_set = true;
  18. condvar.notify_one();
  19. }
  20. }
  21. void Wait() {
  22. std::unique_lock<std::mutex> lk(mutex);
  23. condvar.wait(lk, [&] { return is_set; });
  24. is_set = false;
  25. }
  26. template <class Clock, class Duration>
  27. bool WaitUntil(const std::chrono::time_point<Clock, Duration>& time) {
  28. std::unique_lock<std::mutex> lk(mutex);
  29. if (!condvar.wait_until(lk, time, [this] { return is_set; }))
  30. return false;
  31. is_set = false;
  32. return true;
  33. }
  34. void Reset() {
  35. std::unique_lock<std::mutex> lk(mutex);
  36. // no other action required, since wait loops on the predicate and any lingering signal will
  37. // get cleared on the first iteration
  38. is_set = false;
  39. }
  40. private:
  41. bool is_set = false;
  42. std::condition_variable condvar;
  43. std::mutex mutex;
  44. };
  45. class Barrier {
  46. public:
  47. explicit Barrier(std::size_t count_) : count(count_) {}
  48. /// Blocks until all "count" threads have called Sync()
  49. void Sync() {
  50. std::unique_lock<std::mutex> lk(mutex);
  51. const std::size_t current_generation = generation;
  52. if (++waiting == count) {
  53. generation++;
  54. waiting = 0;
  55. condvar.notify_all();
  56. } else {
  57. condvar.wait(lk,
  58. [this, current_generation] { return current_generation != generation; });
  59. }
  60. }
  61. private:
  62. std::condition_variable condvar;
  63. std::mutex mutex;
  64. std::size_t count;
  65. std::size_t waiting = 0;
  66. std::size_t generation = 0; // Incremented once each time the barrier is used
  67. };
  68. void SetThreadAffinity(std::thread::native_handle_type thread, u32 mask);
  69. void SetCurrentThreadAffinity(u32 mask);
  70. void SwitchCurrentThread(); // On Linux, this is equal to sleep 1ms
  71. void SetCurrentThreadName(const char* name);
  72. } // namespace Common