thread.h 2.4 KB

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