WorkerPool.cpp 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. #include "core/WorkerPool.h"
  2. #include <chrono>
  3. #include "core/Denormals.h"
  4. #if defined(_WIN32)
  5. #ifndef WIN32_LEAN_AND_MEAN
  6. #define WIN32_LEAN_AND_MEAN
  7. #endif
  8. #ifndef NOMINMAX
  9. #define NOMINMAX
  10. #endif
  11. #include <windows.h>
  12. #elif defined(__APPLE__)
  13. #include <dispatch/dispatch.h>
  14. #else
  15. #include <semaphore.h>
  16. #endif
  17. #if defined(__SSE2__) || defined(_M_X64) || defined(__x86_64__)
  18. #include "core/Simd.h"
  19. #endif
  20. namespace lynx
  21. {
  22. namespace
  23. {
  24. inline void cpuRelax() noexcept
  25. {
  26. #if defined(__SSE2__) || defined(_M_X64) || defined(__x86_64__)
  27. _mm_pause();
  28. #elif defined(__aarch64__)
  29. asm volatile ("yield");
  30. #endif
  31. }
  32. } // namespace
  33. #if defined(_WIN32)
  34. struct WorkerPool::Semaphore
  35. {
  36. Semaphore() : handle (CreateSemaphoreW (nullptr, 0, 0x7fffffff, nullptr)) {}
  37. ~Semaphore()
  38. {
  39. if (handle != nullptr)
  40. CloseHandle (handle);
  41. }
  42. void release (int n) noexcept { ReleaseSemaphore (handle, n, nullptr); }
  43. void acquire() noexcept { WaitForSingleObject (handle, INFINITE); }
  44. HANDLE handle;
  45. };
  46. #elif defined(__APPLE__)
  47. // libdispatch semaphore: a Mach semaphore underneath, woken by the kernel at once
  48. struct WorkerPool::Semaphore
  49. {
  50. Semaphore() : handle (dispatch_semaphore_create (0)) {}
  51. ~Semaphore() { dispatch_release (handle); }
  52. void release (int n) noexcept
  53. {
  54. for (int i = 0; i < n; ++i)
  55. dispatch_semaphore_signal (handle);
  56. }
  57. void acquire() noexcept { dispatch_semaphore_wait (handle, DISPATCH_TIME_FOREVER); }
  58. dispatch_semaphore_t handle;
  59. };
  60. #else
  61. // POSIX semaphore: glibc implements it on a futex (uncontended post/wait stay in user space, a sleeper is woken
  62. // by the kernel at once)
  63. struct WorkerPool::Semaphore
  64. {
  65. Semaphore() { sem_init (&handle, 0, 0); }
  66. ~Semaphore() { sem_destroy (&handle); }
  67. void release (int n) noexcept
  68. {
  69. for (int i = 0; i < n; ++i)
  70. sem_post (&handle);
  71. }
  72. void acquire() noexcept
  73. {
  74. while (sem_wait (&handle) != 0) {} // EINTR: a signal interrupted the wait
  75. }
  76. sem_t handle;
  77. };
  78. #endif
  79. WorkerPool::WorkerPool (int n, std::function<void()> onThreadStart) : wake (std::make_unique<Semaphore>())
  80. {
  81. // ticket 0: count 0, nothing to take until the first parallelFor
  82. for (int i = 0; i < n; ++i)
  83. threads.emplace_back ([this, onThreadStart] { workerLoop (onThreadStart); });
  84. }
  85. WorkerPool::~WorkerPool()
  86. {
  87. quit.store (true);
  88. wake->release ((int) threads.size());
  89. for (auto& t : threads)
  90. t.join();
  91. }
  92. bool WorkerPool::hasWork() const noexcept
  93. {
  94. constexpr auto mask = (std::uint64_t (1) << indexBits) - 1;
  95. const auto t = ticket.load (std::memory_order_acquire);
  96. return (t & mask) < ((t >> indexBits) & mask);
  97. }
  98. bool WorkerPool::isParked() const noexcept
  99. {
  100. return (ticket.load (std::memory_order_acquire) >> (2 * indexBits)) == parkedGeneration.load (std::memory_order_acquire);
  101. }
  102. void WorkerPool::workerLoop (std::function<void()> onStart)
  103. {
  104. const ScopedFlushDenormals noDenormals;
  105. if (onStart)
  106. onStart();
  107. using clock = std::chrono::steady_clock;
  108. while (! quit.load (std::memory_order_relaxed))
  109. {
  110. // spin a little: within a block the next parallelFor (next mixer layer or chunk) follows right away
  111. auto spinStart = clock::now();
  112. auto found = false;
  113. for (int i = 0;; ++i)
  114. {
  115. if (hasWork())
  116. {
  117. found = true;
  118. break;
  119. }
  120. cpuRelax();
  121. if ((i & 63) == 63)
  122. {
  123. if (quit.load (std::memory_order_relaxed))
  124. return;
  125. if (isParked()) // the block is over: sleep now
  126. break;
  127. if (clock::now() - spinStart > std::chrono::microseconds (spinMicros))
  128. break;
  129. }
  130. }
  131. if (found)
  132. {
  133. work (true);
  134. continue;
  135. }
  136. // sleep. Announce it first, then look once more: run() publishes the ticket before reading `sleeping`,
  137. // so either it sees this worker asleep and releases the semaphore, or this check sees the work
  138. sleeping.fetch_add (1, std::memory_order_seq_cst);
  139. if (hasWork())
  140. {
  141. sleeping.fetch_sub (1, std::memory_order_seq_cst);
  142. work (true);
  143. continue;
  144. }
  145. wake->acquire();
  146. sleeping.fetch_sub (1, std::memory_order_seq_cst);
  147. wokenUp.fetch_add (1, std::memory_order_relaxed);
  148. if (quit.load())
  149. return;
  150. work (true);
  151. }
  152. }
  153. bool WorkerPool::work (bool isWorker) noexcept
  154. {
  155. constexpr auto mask = (std::uint64_t (1) << indexBits) - 1;
  156. auto any = false;
  157. while (true)
  158. {
  159. const auto t = ticket.fetch_add (1, std::memory_order_acq_rel);
  160. const auto i = t & mask, n = (t >> indexBits) & mask;
  161. if (i >= n)
  162. return any;
  163. call (context, (int) i);
  164. any = true;
  165. if (isWorker)
  166. byWorkers.fetch_add (1, std::memory_order_relaxed);
  167. done.fetch_add (1, std::memory_order_acq_rel);
  168. }
  169. }
  170. void WorkerPool::run (int n, void* ctx, Call fn) noexcept
  171. {
  172. if (n <= 0)
  173. return;
  174. if (n == 1 || threads.empty() || n >= (1 << indexBits))
  175. {
  176. for (int i = 0; i < n; ++i)
  177. fn (ctx, i);
  178. return;
  179. }
  180. context = ctx;
  181. call = fn;
  182. done.store (0, std::memory_order_relaxed);
  183. ++generation;
  184. const auto base = generation << (2 * indexBits);
  185. ticket.store (base | ((std::uint64_t) n << indexBits), std::memory_order_seq_cst); // from here on the workers may take indices
  186. // wake only the sleepers that are needed (spinning workers already see the ticket)
  187. if (const auto asleep = sleeping.load (std::memory_order_seq_cst); asleep > 0)
  188. wake->release (std::min (asleep, n - 1));
  189. work (false);
  190. for (int spins = 0; done.load (std::memory_order_acquire) < n; ++spins)
  191. {
  192. cpuRelax();
  193. if ((spins & 1023) == 1023)
  194. std::this_thread::yield();
  195. }
  196. ticket.store (base, std::memory_order_release); // count 0: late workers take nothing
  197. }
  198. } // namespace lynx