WorkerPool.h 4.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #pragma once
  2. // Thread pool for the audio thread to split a block's work (channels and
  3. // mixer tracks), like FL does with the mixer layers (docs/ANALISE_FL_STUDIO.md §2.2).
  4. // parallelFor neither allocates nor blocks on a mutex: workers take indices from an atomic counter; the calling
  5. // thread also works and spin-waits for the last index.
  6. //
  7. // Waking the workers (REA round 87): a worker that just finished spins for a short while (the next parallelFor of
  8. // the same block — the next mixer layer, the next chunk — comes microseconds later), then sleeps on an OS
  9. // semaphore (a Win32 semaphore on Windows, a libdispatch one on macOS, a futex-backed POSIX one on Linux). std::counting_semaphore is NOT used:
  10. // the Windows libc++ build has no platform wait and falls back to Sleep() polling with growing intervals, so an
  11. // idle worker woke 1–8 ms late — later than a whole audio block — and the audio thread ended up doing all the
  12. // work alone.
  13. //
  14. // Parking (REA round 116): the spin only pays off between the parallelFor calls of one block. After the block's last
  15. // one, park() sends the spinning workers to sleep at once; otherwise every worker burned ~250 µs per audio block
  16. // (7 workers × 172 blocks/s at 256 samples ≈ 30 % of a core) even with the transport stopped.
  17. #include <atomic>
  18. #include <cstdint>
  19. #include <functional>
  20. #include <memory>
  21. #include <thread>
  22. #include <vector>
  23. namespace lynx
  24. {
  25. class WorkerPool
  26. {
  27. public:
  28. // `threads` workers besides the calling thread. `onThreadStart` runs on each worker
  29. // (e.g. raising the priority); may be empty.
  30. explicit WorkerPool (int threads, std::function<void()> onThreadStart = {});
  31. ~WorkerPool();
  32. WorkerPool (const WorkerPool&) = delete;
  33. WorkerPool& operator= (const WorkerPool&) = delete;
  34. int workers() const noexcept { return (int) threads.size(); }
  35. // Calls fn(i) for i in [0, count), in parallel. Returns when all have finished.
  36. template <typename Fn>
  37. void parallelFor (int count, Fn& fn) noexcept
  38. {
  39. run (count, &fn, [] (void* f, int i) { (*static_cast<Fn*> (f)) (i); });
  40. }
  41. // The caller's block is finished (no more parallelFor until the next audio callback): spinning workers go to
  42. // sleep now instead of polling until spinMicros runs out. Wait-free; the next parallelFor wakes them as usual.
  43. void park() noexcept { parkedGeneration.store (generation, std::memory_order_release); }
  44. // How long a worker keeps polling for new work after finishing before it sleeps (microseconds). REA round 116
  45. // measured 250 → 60 on Windows (FL Studio ASIO, 256 samples, Thief / Exoplanet playing): process CPU 106/114 % →
  46. // 70/90 % of a core, the callback's average and peak load unchanged (the gaps between one block's parallelFor
  47. // calls are usually far shorter than 60 µs; a longer one costs a semaphore wake-up)
  48. static constexpr int spinMicros = 60;
  49. // Diagnostics: how many indices the workers (not the calling thread) ran, and how many times a worker
  50. // was woken from sleep. Relaxed counters.
  51. std::uint64_t indicesRunByWorkers() const noexcept { return byWorkers.load (std::memory_order_relaxed); }
  52. std::uint64_t wakeUps() const noexcept { return wokenUp.load (std::memory_order_relaxed); }
  53. private:
  54. using Call = void (*) (void*, int);
  55. void run (int count, void* context, Call call) noexcept;
  56. bool work (bool isWorker) noexcept;
  57. bool hasWork() const noexcept;
  58. bool isParked() const noexcept;
  59. void workerLoop (std::function<void()> onStart);
  60. struct Semaphore; // OS semaphore (WorkerPool.cpp)
  61. std::unique_ptr<Semaphore> wake;
  62. std::vector<std::thread> threads;
  63. std::atomic<bool> quit { false };
  64. std::atomic<int> sleeping { 0 }; // workers blocked (or about to block) on `wake`
  65. // the generation (see `ticket`) of the last parallelFor before park(); while the ticket still carries it,
  66. // the pool is parked and a worker without work sleeps instead of spinning
  67. std::atomic<std::uint64_t> parkedGeneration { ~std::uint64_t (0) };
  68. // current work (published before `ticket`). The ticket packs generation (bits 40+), count (bits 20…39) and the
  69. // next index (bits 0…19), so an index taken by a late worker always carries its own round's count: a worker
  70. // that stalls between taking an index and running it can never run an index of a later round (no ABA)
  71. void* context = nullptr;
  72. Call call = nullptr;
  73. static constexpr int indexBits = 20;
  74. std::atomic<std::uint64_t> ticket { 0 };
  75. std::uint64_t generation = 0; // caller thread only
  76. std::atomic<int> done { 0 };
  77. std::atomic<std::uint64_t> byWorkers { 0 }, wokenUp { 0 };
  78. };
  79. } // namespace lynx