WorkerPool.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. #include "core/WorkerPool.h"
  2. #include <algorithm>
  3. #include <chrono>
  4. #include <cstdio>
  5. #include <cstdlib>
  6. #include <cstring>
  7. #include <ctime>
  8. #include "core/Denormals.h"
  9. #if defined(_WIN32)
  10. #ifndef WIN32_LEAN_AND_MEAN
  11. #define WIN32_LEAN_AND_MEAN
  12. #endif
  13. #ifndef NOMINMAX
  14. #define NOMINMAX
  15. #endif
  16. #include <windows.h>
  17. #elif defined(__APPLE__)
  18. #include <dispatch/dispatch.h>
  19. #include <pthread.h>
  20. #else
  21. #include <pthread.h>
  22. #include <semaphore.h>
  23. #endif
  24. #if defined(__SSE2__) || defined(_M_X64) || defined(__x86_64__)
  25. #include "core/Simd.h"
  26. #endif
  27. namespace lynx
  28. {
  29. namespace
  30. {
  31. inline void cpuRelax() noexcept
  32. {
  33. #if defined(__SSE2__) || defined(_M_X64) || defined(__x86_64__)
  34. _mm_pause();
  35. #elif defined(__aarch64__)
  36. asm volatile ("yield");
  37. #endif
  38. }
  39. } // namespace
  40. #if defined(_WIN32)
  41. struct OsSemaphore::Impl
  42. {
  43. Impl() : handle (CreateSemaphoreW (nullptr, 0, 0x7fffffff, nullptr)) {}
  44. ~Impl()
  45. {
  46. if (handle != nullptr)
  47. CloseHandle (handle);
  48. }
  49. void release (int n) noexcept { ReleaseSemaphore (handle, n, nullptr); }
  50. void acquire() noexcept { WaitForSingleObject (handle, INFINITE); }
  51. HANDLE handle;
  52. };
  53. #elif defined(__APPLE__)
  54. // libdispatch semaphore: a Mach semaphore underneath, woken by the kernel at once
  55. struct OsSemaphore::Impl
  56. {
  57. Impl() : handle (dispatch_semaphore_create (0)) {}
  58. ~Impl() { dispatch_release (handle); }
  59. void release (int n) noexcept
  60. {
  61. for (int i = 0; i < n; ++i)
  62. dispatch_semaphore_signal (handle);
  63. }
  64. void acquire() noexcept { dispatch_semaphore_wait (handle, DISPATCH_TIME_FOREVER); }
  65. dispatch_semaphore_t handle;
  66. };
  67. #else
  68. // POSIX semaphore: glibc implements it on a futex (uncontended post/wait stay in user space, a sleeper is woken
  69. // by the kernel at once)
  70. struct OsSemaphore::Impl
  71. {
  72. Impl() { sem_init (&handle, 0, 0); }
  73. ~Impl() { sem_destroy (&handle); }
  74. void release (int n) noexcept
  75. {
  76. for (int i = 0; i < n; ++i)
  77. sem_post (&handle);
  78. }
  79. void acquire() noexcept
  80. {
  81. while (sem_wait (&handle) != 0) {} // EINTR: a signal interrupted the wait
  82. }
  83. sem_t handle;
  84. };
  85. #endif
  86. OsSemaphore::OsSemaphore() : impl (std::make_unique<Impl>()) {}
  87. OsSemaphore::~OsSemaphore() = default;
  88. void OsSemaphore::release (int n) noexcept
  89. {
  90. if (n > 0)
  91. impl->release (n);
  92. }
  93. void OsSemaphore::acquire() noexcept { impl->acquire(); }
  94. void WorkerPool::relax() noexcept
  95. {
  96. cpuRelax();
  97. }
  98. std::uint64_t WorkerPool::threadCpuNs() noexcept
  99. {
  100. #if defined(_WIN32)
  101. FILETIME created, exited, kernel, user;
  102. if (! GetThreadTimes (GetCurrentThread(), &created, &exited, &kernel, &user))
  103. return 0;
  104. const auto k = ((std::uint64_t) kernel.dwHighDateTime << 32) | kernel.dwLowDateTime;
  105. const auto u = ((std::uint64_t) user.dwHighDateTime << 32) | user.dwLowDateTime;
  106. return (k + u) * 100;
  107. #else
  108. timespec ts {};
  109. if (clock_gettime (CLOCK_THREAD_CPUTIME_ID, &ts) != 0)
  110. return 0;
  111. return (std::uint64_t) ts.tv_sec * 1000000000ull + (std::uint64_t) ts.tv_nsec;
  112. #endif
  113. }
  114. namespace
  115. {
  116. // round 190kb: the lane of the calling thread (a worker's own, or the caller's while it runs a round)
  117. thread_local const WorkerPool* lanePool = nullptr;
  118. thread_local int laneIndex = -1;
  119. int parsedValue (const char* spec, const char* key, int fallback) noexcept
  120. {
  121. const auto length = std::strlen (key);
  122. for (const char* at = spec; at != nullptr && *at != 0;)
  123. {
  124. if (std::strncmp (at, key, length) == 0 && at[length] == '=')
  125. return std::atoi (at + length + 1);
  126. at = std::strchr (at, ',');
  127. if (at != nullptr)
  128. ++at;
  129. }
  130. return fallback;
  131. }
  132. } // namespace
  133. void WorkerPool::nameCurrentThread (const char* text) noexcept
  134. {
  135. #if defined(_WIN32)
  136. using SetDescription = HRESULT (WINAPI*) (HANDLE, PCWSTR);
  137. static const auto set = (SetDescription) (void*) GetProcAddress (GetModuleHandleW (L"kernel32.dll"), "SetThreadDescription");
  138. if (set != nullptr)
  139. {
  140. wchar_t name[64] {};
  141. for (int k = 0; k < 63 && text[k] != 0; ++k)
  142. name[k] = (wchar_t) (unsigned char) text[k];
  143. set (GetCurrentThread(), name);
  144. }
  145. #elif defined(__linux__)
  146. char name[16] {};
  147. std::strncpy (name, text, sizeof (name) - 1);
  148. pthread_setname_np (pthread_self(), name);
  149. #elif defined(__APPLE__)
  150. pthread_setname_np (text);
  151. #endif
  152. }
  153. WorkerPool::Tuning& WorkerPool::tuning() noexcept
  154. {
  155. static Tuning t;
  156. static const bool fromEnvironment = [] {
  157. if (const char* e = std::getenv ("LYNX_POOL"); e != nullptr)
  158. t.apply (e);
  159. return true;
  160. }();
  161. (void) fromEnvironment;
  162. return t;
  163. }
  164. void WorkerPool::Tuning::apply (const char* spec) noexcept
  165. {
  166. if (spec == nullptr)
  167. return;
  168. workerSpinMicros.store (std::clamp (parsedValue (spec, "spin", workerSpinMicros.load()), 0, 10000));
  169. drySpinMicros.store (std::clamp (parsedValue (spec, "dry", drySpinMicros.load()), 0, 10000));
  170. adaptiveSpin.store (parsedValue (spec, "adaptive", adaptiveSpin.load() ? 1 : 0) != 0);
  171. waitMode.store (std::clamp (parsedValue (spec, "wait", waitMode.load()), 0, 2));
  172. waitSpinMicros.store (std::clamp (parsedValue (spec, "waitspin", waitSpinMicros.load()), 0, 10000));
  173. helpPercent.store (std::clamp (parsedValue (spec, "help", helpPercent.load()), 0, 1000));
  174. liveRounds.store (parsedValue (spec, "live", liveRounds.load()) != 0 ? 1 : 0);
  175. // (round 190kz: "rounds=chunk" / "rounds=block", or 0 / 1)
  176. for (const char* at = spec; at != nullptr && *at != 0;)
  177. {
  178. if (std::strncmp (at, "rounds=", 7) == 0)
  179. {
  180. const char* v = at + 7;
  181. if (std::strncmp (v, "chunk", 5) == 0)
  182. blockRounds.store (0);
  183. else if (std::strncmp (v, "block", 5) == 0)
  184. blockRounds.store (1);
  185. else
  186. blockRounds.store (std::atoi (v) != 0 ? 1 : 0);
  187. }
  188. at = std::strchr (at, ',');
  189. if (at != nullptr)
  190. ++at;
  191. }
  192. }
  193. WorkerPool::Stats WorkerPool::stats() const noexcept
  194. {
  195. Stats s;
  196. s.rounds = roundsRun.load (std::memory_order_relaxed);
  197. for (int k = 0; k < laneCount; ++k)
  198. {
  199. const auto& l = lanes[(std::size_t) k];
  200. const auto r = [] (const std::atomic<std::uint64_t>& a) { return a.load (std::memory_order_relaxed); };
  201. s.workNs += r (l.workNs);
  202. s.spinNs += r (l.spinNs);
  203. s.spins += r (l.spins);
  204. s.spinFound += r (l.spinFound);
  205. s.spinParked += r (l.spinParked);
  206. s.spinTimedOut += r (l.spinTimedOut);
  207. s.sleeps += r (l.sleeps);
  208. s.earlyWakes += r (l.earlyWakes);
  209. s.waitNs += r (l.waitNs);
  210. s.waits += r (l.waits);
  211. s.waitYields += r (l.waitYields);
  212. s.waitSleeps += r (l.waitSleeps);
  213. s.waitSleepNs += r (l.waitSleepNs);
  214. s.callerWaitNs += r (l.callerWaitNs);
  215. s.callerSleeps += r (l.callerSleeps);
  216. }
  217. return s;
  218. }
  219. WorkerPool::Lane* WorkerPool::currentLane() const noexcept
  220. {
  221. return lanePool == this && laneIndex >= 0 && laneIndex < laneCount ? &lanes[(std::size_t) laneIndex] : nullptr;
  222. }
  223. void WorkerPool::awaitSlow (int key, void* ready, ReadyFn fn) noexcept
  224. {
  225. using clock = std::chrono::steady_clock;
  226. auto& t = tuning();
  227. auto* lane = currentLane();
  228. // (a thread outside this pool's round can't be woken by notify: it spins as before)
  229. const auto mode = lane != nullptr ? t.waitMode.load (std::memory_order_relaxed) : 0;
  230. const auto spinFor = std::chrono::microseconds (t.waitSpinMicros.load (std::memory_order_relaxed));
  231. const auto start = clock::now();
  232. std::uint64_t yields = 0, sleeps = 0, sleptNs = 0;
  233. for (int spins = 0; ! fn (ready); ++spins)
  234. {
  235. cpuRelax();
  236. if (mode == 0)
  237. {
  238. if ((spins & 1023) == 1023)
  239. {
  240. std::this_thread::yield();
  241. ++yields;
  242. }
  243. continue;
  244. }
  245. if ((spins & 63) != 63 || clock::now() - start < spinFor)
  246. continue;
  247. // sleep. Announce the key first, then look once more: notify() publishes its result before it reads
  248. // `waitSleepers`, so either it sees this thread asleep and takes the key, or this check sees the result
  249. lane->sleepKey.store (key, std::memory_order_seq_cst);
  250. waitSleepers.fetch_add (1, std::memory_order_seq_cst);
  251. if (fn (ready))
  252. {
  253. if (lane->sleepKey.exchange (-1, std::memory_order_acq_rel) == -1)
  254. lane->sleep.acquire(); // (a notify took the key at the same moment: its wake-up is ours to take)
  255. waitSleepers.fetch_sub (1, std::memory_order_seq_cst);
  256. break;
  257. }
  258. const auto asleep = clock::now();
  259. lane->sleep.acquire();
  260. waitSleepers.fetch_sub (1, std::memory_order_seq_cst);
  261. ++sleeps;
  262. sleptNs += (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (clock::now() - asleep).count();
  263. spins = 0; // (woken: the result is there; should it not be, spin and sleep again)
  264. }
  265. if (lane != nullptr)
  266. {
  267. bump (lane->waitNs, (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (clock::now() - start).count());
  268. bump (lane->waits, 1);
  269. bump (lane->waitYields, yields);
  270. bump (lane->waitSleeps, sleeps);
  271. bump (lane->waitSleepNs, sleptNs);
  272. }
  273. }
  274. void WorkerPool::noteWait (std::uint64_t ns, bool handedOff) noexcept
  275. {
  276. if (auto* lane = currentLane())
  277. {
  278. bump (lane->waitNs, ns);
  279. bump (lane->waits, 1);
  280. if (handedOff)
  281. bump (lane->waitSleeps, 1);
  282. }
  283. }
  284. void WorkerPool::notifySlow (int key) noexcept
  285. {
  286. for (int k = 0; k < laneCount; ++k)
  287. {
  288. auto expected = key;
  289. if (lanes[(std::size_t) k].sleepKey.compare_exchange_strong (expected, -1, std::memory_order_acq_rel))
  290. lanes[(std::size_t) k].sleep.release();
  291. }
  292. }
  293. WorkerPool::WorkerPool (int n, std::function<void()> onThreadStart) : wake (std::make_unique<OsSemaphore>())
  294. {
  295. // ticket 0: count 0, nothing to take until the first parallelFor
  296. laneCount = std::max (0, n) + 1;
  297. lanes = std::make_unique<Lane[]> ((std::size_t) laneCount);
  298. for (int i = 0; i < n; ++i)
  299. threads.emplace_back ([this, i, onThreadStart] { workerLoop (i, onThreadStart); });
  300. }
  301. WorkerPool::~WorkerPool()
  302. {
  303. quit.store (true);
  304. wake->release ((int) threads.size());
  305. for (auto& t : threads)
  306. t.join();
  307. }
  308. void WorkerPool::setThreadRefresh (std::function<void()> fn)
  309. {
  310. threadRefresh = std::move (fn); // (the workers read it only after a request: its release publishes it)
  311. }
  312. void WorkerPool::refreshIfAsked (std::uint32_t& seen) const
  313. {
  314. if (const auto now = refreshGeneration.load (std::memory_order_acquire); now != seen)
  315. {
  316. seen = now;
  317. if (threadRefresh)
  318. threadRefresh();
  319. }
  320. }
  321. bool WorkerPool::hasWork() const noexcept
  322. {
  323. constexpr auto mask = (std::uint64_t (1) << indexBits) - 1;
  324. const auto t = ticket.load (std::memory_order_acquire);
  325. return (t & mask) < ((t >> indexBits) & mask);
  326. }
  327. bool WorkerPool::isParked() const noexcept
  328. {
  329. return (ticket.load (std::memory_order_acquire) >> (2 * indexBits)) == parkedGeneration.load (std::memory_order_acquire);
  330. }
  331. void WorkerPool::workerLoop (int index, std::function<void()> onStart)
  332. {
  333. const ScopedFlushDenormals noDenormals;
  334. {
  335. char name[32];
  336. std::snprintf (name, sizeof (name), "LYNX worker %d", index + 1);
  337. nameCurrentThread (name);
  338. }
  339. lanePool = this;
  340. laneIndex = index;
  341. auto& lane = lanes[(std::size_t) index];
  342. auto& tune = tuning();
  343. if (onStart)
  344. onStart();
  345. using clock = std::chrono::steady_clock;
  346. const auto ns = [] (clock::duration d) { return (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (d).count(); };
  347. std::uint32_t refreshSeen = 0; // (the generation the pool started with: a request made before this thread ran counts too)
  348. auto cpuMark = threadCpuNs();
  349. int dry = 0; // round 190kb: spins in a row that found no work
  350. constexpr int dryEpisodes = 4;
  351. auto timedWork = [&] (clock::time_point from) {
  352. work (true);
  353. const auto end = clock::now();
  354. bump (lane.workNs, ns (end - from));
  355. return end;
  356. };
  357. auto spinStart = clock::now();
  358. while (! quit.load (std::memory_order_relaxed))
  359. {
  360. refreshIfAsked (refreshSeen);
  361. // spin a little: within a block the next parallelFor (next mixer layer or chunk) follows right away. Round
  362. // 190kb: after a few dry spins (one parallelFor per block, the task graph: the next round is a whole block
  363. // away) only a short one; the full spin returns once a wake-up comes within it
  364. const auto fullSpin = std::chrono::microseconds (tune.workerSpinMicros.load (std::memory_order_relaxed));
  365. const auto spinFor = tune.adaptiveSpin.load (std::memory_order_relaxed) && dry >= dryEpisodes
  366. ? std::min (fullSpin, std::chrono::microseconds (tune.drySpinMicros.load (std::memory_order_relaxed)))
  367. : fullSpin;
  368. auto found = false, parked = false;
  369. auto spinEnd = spinStart;
  370. for (int i = 0;; ++i)
  371. {
  372. if (hasWork())
  373. {
  374. found = true;
  375. break;
  376. }
  377. cpuRelax();
  378. if ((i & 63) == 63)
  379. {
  380. if (quit.load (std::memory_order_relaxed))
  381. return;
  382. if (isParked()) // the block is over: sleep now
  383. {
  384. parked = true;
  385. break;
  386. }
  387. if ((spinEnd = clock::now()) - spinStart > spinFor)
  388. break;
  389. }
  390. }
  391. if (found || parked)
  392. spinEnd = clock::now();
  393. bump (lane.spinNs, ns (spinEnd - spinStart));
  394. bump (lane.spins, 1);
  395. bump (found ? lane.spinFound : parked ? lane.spinParked : lane.spinTimedOut, 1);
  396. if (found)
  397. {
  398. dry = 0;
  399. spinStart = timedWork (spinEnd);
  400. const auto now = threadCpuNs(); // (round 190gq: the workers' CPU, spinning included)
  401. workersCpu.fetch_add (now - cpuMark, std::memory_order_relaxed);
  402. cpuMark = now;
  403. continue;
  404. }
  405. if (! parked)
  406. ++dry;
  407. // sleep. Announce it first, then look once more: run() publishes the ticket before reading `sleeping`,
  408. // so either it sees this worker asleep and releases the semaphore, or this check sees the work
  409. sleeping.fetch_add (1, std::memory_order_seq_cst);
  410. if (hasWork())
  411. {
  412. sleeping.fetch_sub (1, std::memory_order_seq_cst);
  413. spinStart = timedWork (clock::now());
  414. continue;
  415. }
  416. {
  417. const auto now = threadCpuNs();
  418. workersCpu.fetch_add (now - cpuMark, std::memory_order_relaxed);
  419. wake->acquire();
  420. cpuMark = threadCpuNs();
  421. }
  422. sleeping.fetch_sub (1, std::memory_order_seq_cst);
  423. wokenUp.fetch_add (1, std::memory_order_relaxed);
  424. bump (lane.sleeps, 1);
  425. const auto woke = clock::now();
  426. // (round 190kb) woken within what the full spin would have waited: spinning pays off again
  427. if (! parked && woke - spinStart <= fullSpin)
  428. {
  429. dry = 0;
  430. bump (lane.earlyWakes, 1);
  431. }
  432. if (quit.load())
  433. return;
  434. refreshIfAsked (refreshSeen); // (before the block's work: a new workgroup is joined before working for it)
  435. spinStart = timedWork (woke);
  436. }
  437. }
  438. bool WorkerPool::work (bool isWorker) noexcept
  439. {
  440. constexpr auto mask = (std::uint64_t (1) << indexBits) - 1;
  441. auto any = false;
  442. // (round 190gq, 190gs Q5) the indices this batch ran, added to `done` once when the batch ends — before the round
  443. // can end, since the caller waits for all of them — and kept apart per round in case a ticket of the next one
  444. // comes up in the same loop
  445. int ran = 0;
  446. std::uint64_t ranGeneration = 0;
  447. auto flush = [&] {
  448. if (ran == 0)
  449. return;
  450. if (isWorker)
  451. byWorkers.fetch_add ((std::uint64_t) ran, std::memory_order_relaxed);
  452. if (done.fetch_add (ran, std::memory_order_acq_rel) + ran == target && callerWaiting.exchange (false, std::memory_order_acq_rel))
  453. finished->release(); // (the last of the round: the caller sleeps)
  454. ran = 0;
  455. };
  456. while (true)
  457. {
  458. const auto t = ticket.fetch_add (1, std::memory_order_acq_rel);
  459. const auto i = t & mask, n = (t >> indexBits) & mask, g = t >> (2 * indexBits);
  460. if (ran > 0 && g != ranGeneration)
  461. flush();
  462. if (i >= n)
  463. {
  464. flush();
  465. return any;
  466. }
  467. call (context, (int) i);
  468. any = true;
  469. ranGeneration = g;
  470. ++ran;
  471. }
  472. }
  473. void WorkerPool::run (int n, void* ctx, Call fn) noexcept
  474. {
  475. if (n <= 0)
  476. return;
  477. if (n == 1 || threads.empty() || n >= (1 << indexBits))
  478. {
  479. for (int i = 0; i < n; ++i)
  480. fn (ctx, i);
  481. return;
  482. }
  483. // round 190kb: the caller's lane while it works on this round (await() inside its indices can sleep on it)
  484. struct CallerLane
  485. {
  486. const WorkerPool* pool;
  487. int index;
  488. ~CallerLane() { lanePool = pool, laneIndex = index; }
  489. } restore { lanePool, laneIndex };
  490. lanePool = this;
  491. laneIndex = laneCount - 1;
  492. auto& lane = lanes[(std::size_t) laneCount - 1];
  493. roundsRun.store (roundsRun.load (std::memory_order_relaxed) + 1, std::memory_order_relaxed);
  494. context = ctx;
  495. call = fn;
  496. target = n;
  497. done.store (0, std::memory_order_relaxed);
  498. ++generation;
  499. const auto base = generation << (2 * indexBits);
  500. ticket.store (base | ((std::uint64_t) n << indexBits), std::memory_order_seq_cst); // from here on the workers may take indices
  501. // wake only the sleepers that are needed (spinning workers already see the ticket)
  502. if (const auto asleep = sleeping.load (std::memory_order_seq_cst); asleep > 0)
  503. {
  504. const auto limit = wakeLimit.load (std::memory_order_relaxed); // (round 190kr)
  505. if (const auto wanted = std::min ({ asleep, n - 1, limit < 0 ? n : limit }); wanted > 0)
  506. wake->release (wanted);
  507. }
  508. work (false);
  509. // (round 190gq) a short spin for the last indices, then sleep until the worker finishing the round wakes us
  510. // (LYNX_CALLER_SLEEP=0: the old spin-and-yield wait, for A/B runs)
  511. static const bool callerSleeps = [] { const char* e = std::getenv ("LYNX_CALLER_SLEEP"); return e == nullptr || std::atoi (e) != 0; }();
  512. if (! callerSleeps)
  513. for (int spins = 0; done.load (std::memory_order_acquire) < n; ++spins)
  514. {
  515. cpuRelax();
  516. if ((spins & 1023) == 1023)
  517. std::this_thread::yield();
  518. }
  519. if (done.load (std::memory_order_acquire) < n)
  520. {
  521. const auto waitStart = std::chrono::steady_clock::now();
  522. struct Timed
  523. {
  524. Lane& lane;
  525. std::chrono::steady_clock::time_point start;
  526. ~Timed() { bump (lane.callerWaitNs, (std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::steady_clock::now() - start).count()); }
  527. } timed { lane, waitStart };
  528. const auto spinUntil = waitStart + std::chrono::microseconds (callerSpinMicros);
  529. for (int spins = 0; done.load (std::memory_order_acquire) < n; ++spins)
  530. {
  531. cpuRelax();
  532. if ((spins & 63) == 63 && std::chrono::steady_clock::now() > spinUntil)
  533. {
  534. callerWaiting.store (true, std::memory_order_seq_cst);
  535. if (done.load (std::memory_order_seq_cst) >= n)
  536. {
  537. // finished meanwhile: take back the flag, or the wake already sent for it
  538. if (! callerWaiting.exchange (false, std::memory_order_acq_rel))
  539. finished->acquire();
  540. break;
  541. }
  542. finished->acquire();
  543. bump (lane.callerSleeps, 1);
  544. break;
  545. }
  546. }
  547. }
  548. ticket.store (base, std::memory_order_release); // count 0: late workers take nothing
  549. }
  550. } // namespace lynx