thread.h 2.6 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. 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(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 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 size_t count;
  69. size_t waiting;
  70. 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. // Use this function during a spin-wait to make the current thread
  75. // relax while another thread is working. This may be more efficient
  76. // than using events because event functions use kernel calls.
  77. inline void YieldCPU() {
  78. std::this_thread::yield();
  79. }
  80. void SetCurrentThreadName(const char* name);
  81. } // namespace Common