Просмотр исходного кода

Multicore: serial chains as one task, the caller sleeps instead of spinning, parallel by deadline share (REA 190hb/190hc)

- Task graph (REA 190hb, FL's mixer threading runs each serial chain of tracks as one unit): a task whose only
  successor is fed by nothing else runs that successor itself, so a chain costs no hand-off per link (inserts50, a
  50-insert chain, is one task now). LYNX_CHAINS=0: off.
- WorkerPool::run (REA 190hb: FL's caller never spins): the caller spins 20 µs for the last indices, then sleeps on a
  semaphore that the index completing the round releases (one wake per wait, never a stale one). LYNX_CALLER_SLEEP=0:
  the old spin-and-yield wait.
- The measured multicore switch (REA 190hc) goes parallel when a chunk's measured serial work would fill more than 60 %
  of its real time; a hand-off's worth (the first version) sent Patience's small units and inserts50's chain to the
  workers and cost CPU and overruns.
All scheduling only: the same samples (serial / 3 workers hashes identical on demo, synth100, Thief, Exoplanet,
inserts50, Patience).
Ka1-S 3 недель назад
Родитель
Сommit
68abfc85d9
4 измененных файлов с 71 добавлено и 9 удалено
  1. 27 4
      src/core/RackRenderer.cpp
  2. 5 0
      src/core/RackRenderer.h
  3. 33 5
      src/core/WorkerPool.cpp
  4. 6 0
      src/core/WorkerPool.h

+ 27 - 4
src/core/RackRenderer.cpp

@@ -1293,6 +1293,17 @@ void RackState::buildTaskGraph (const std::vector<int>& depth)
     for (int i = 0; i < tasks; ++i)
         if (graphIndegree[(std::size_t) i] == 0)
             graphRoots.push_back (i);
+    // serial chains (round 190gq): a task whose only successor is fed by nothing else runs that successor itself
+    graphFused.assign ((std::size_t) tasks, -1);
+    graphFusedCount = 0;
+    if (std::getenv ("LYNX_CHAINS") == nullptr || std::atoi (std::getenv ("LYNX_CHAINS")) != 0)
+        for (int i = 0; i < tasks; ++i)
+            if (graphNextStart[(std::size_t) i + 1] - graphNextStart[(std::size_t) i] == 1)
+                if (const auto j = graphNext[(std::size_t) graphNextStart[(std::size_t) i]]; graphIndegree[(std::size_t) j] == 1)
+                {
+                    graphFused[(std::size_t) i] = j;
+                    ++graphFusedCount;
+                }
     graphOk = true;
 }
 
@@ -4169,6 +4180,7 @@ constexpr std::uint64_t lightChunkNs = 60000; // 60 µs (about 1 % of a 256-samp
 // workers at 64 samples at ~110 µs of CPU per block in a light project), a mixer layer below layerSerialNs too, and the
 // channel pass hands out clusters of about clusterWorkNs
 constexpr std::uint64_t serialWorkNs = 150000, layerSerialNs = 30000, clusterWorkNs = 20000;
+constexpr double parallelShare = 0.6; // (round 190gq, REA 190hc: a snapshot that guessed "serial" goes parallel past this)
 // LYNX_A7=0: the round 190ge dispatch (A/B measurements with one build, as LYNX_TASKGRAPH)
 bool adaptiveThreads() noexcept
 {
@@ -4465,8 +4477,8 @@ void RackRenderer::processChunk (const RackState& state, bool playing, double st
     // or not, so the next chunk decides on fresh numbers.
     // Round 190gq (REA 190hc action 1): whether the work goes to the workers at all is measured too. The snapshot's
     // guess (2+ hosted plugins or 24+ channels) left a set of LYNX's own devices (Live's "Patience", 15 tracks) on one
-    // thread at 104-110 % of its deadline with every worker idle: a chunk whose units did at least a hand-off's worth
-    // of work last time runs in parallel whatever its plugin and channel counts.
+    // thread at 104-110 % of its deadline with every worker idle: a chunk whose units' work last time would fill most of
+    // its real time runs in parallel whatever its plugin and channel counts.
     measureUnits = pool != nullptr && adaptiveThreads();
     parallelChunk = state.parallel;
     if (adaptiveThreads() && workers != nullptr)
@@ -4477,7 +4489,11 @@ void RackRenderer::processChunk (const RackState& state, bool playing, double st
             work += channelCostNs[(std::size_t) c];
         for (int t = 1; t < tracks && t < maxMixerTracks; ++t)
             work += trackCostNs[(std::size_t) t];
-        parallelChunk = state.parallel || work >= serialWorkNs;
+        // (the snapshot's guess, with A7's serial rule below; or, whatever the counts, when the chunk's measured work
+        // would take more than parallelShare of its real time on one thread: parallelism pays only near the deadline —
+        // measured: Patience at 64 samples, 53 % of a core in small units, cost more CPU and more overruns in parallel)
+        const auto chunkNs = sampleRate > 0.0 ? 1.0e9 * numSamples / sampleRate : 0.0;
+        parallelChunk = state.parallel || (double) work >= parallelShare * chunkNs;
         if (events.size() == 0 && work < serialWorkNs && (liveInput == nullptr || liveInput->numChannels == 0))
             workers = nullptr;
     }
@@ -4881,6 +4897,8 @@ bool RackRenderer::runTaskGraph (const RackState& state, bool playing, int chann
                 std::this_thread::yield();
         }
         --id;
+        for (;;) // (a serial chain runs here link after link: round 190gq)
+        {
         const auto before = timing || measureUnits ? ProcessTimes::now() : 0; // (A7: every task's time, for the next chunk's choice)
         if (id < channels)
         {
@@ -4903,6 +4921,11 @@ bool RackRenderer::runTaskGraph (const RackState& state, bool playing, int chann
             if (measureUnits && t < maxMixerTracks)
                 trackCostNs[(std::size_t) t] = (std::uint32_t) std::min<std::uint64_t> (ProcessTimes::now() - before, 0xffffffffu);
         }
+        const auto fused = (std::size_t) id < state.graphFused.size() ? state.graphFused[(std::size_t) id] : -1;
+        if (fused < 0)
+            break;
+        id = fused;
+        }
         for (auto k = state.graphNextStart[(std::size_t) id]; k < state.graphNextStart[(std::size_t) id + 1]; ++k)
         {
             const auto j = state.graphNext[(std::size_t) k];
@@ -4910,7 +4933,7 @@ bool RackRenderer::runTaskGraph (const RackState& state, bool playing, int chann
                 graphSlots[(std::size_t) graphPushed.fetch_add (1, std::memory_order_acq_rel)].store (j + 1, std::memory_order_release);
         }
     };
-    workers->parallelFor (tasks, task);
+    workers->parallelFor (tasks - state.graphFusedCount, task);
 
     // the Master's own channels and input (its effects run after, as before)
     sumChannelsInto (state, 0, channels, n);

+ 5 - 0
src/core/RackRenderer.h

@@ -255,6 +255,11 @@ struct RackState
     std::vector<int> graphIndegree;                   // [task] tasks that must finish first
     std::vector<int> graphNextStart, graphNext;       // [task] → successors (CSR)
     std::vector<int> graphRoots;                      // tasks with nothing before them, heaviest kind first
+    // Round 190gq (REA 190hb, FL's mixer threading runs each serial chain of tracks as one unit): [task] the task run
+    // right after it on the same thread (its only successor, which nothing else feeds), −1 none; those tasks are not
+    // handed out on their own (graphFusedCount of them), so a chain costs no hand-off per link
+    std::vector<int> graphFused;
+    int graphFusedCount = 0;
     std::vector<std::vector<int>> trackChannels;      // [track] the channels playing into it, in channel order
     void buildMixerGraph();
     void applyVcas(); // VCA mutes into mixerAudible, the VCA chains (round 177a)

+ 33 - 5
src/core/WorkerPool.cpp

@@ -1,6 +1,7 @@
 #include "core/WorkerPool.h"
 
 #include <chrono>
+#include <cstdlib>
 #include <ctime>
 
 #include "core/Denormals.h"
@@ -231,7 +232,8 @@ bool WorkerPool::work (bool isWorker) noexcept
             return;
         if (isWorker)
             byWorkers.fetch_add ((std::uint64_t) ran, std::memory_order_relaxed);
-        done.fetch_add (ran, std::memory_order_acq_rel);
+        if (done.fetch_add (ran, std::memory_order_acq_rel) + ran == target && callerWaiting.exchange (false, std::memory_order_acq_rel))
+            finished->release(); // (the last of the round: the caller sleeps)
         ran = 0;
     };
 
@@ -269,6 +271,7 @@ void WorkerPool::run (int n, void* ctx, Call fn) noexcept
 
     context = ctx;
     call = fn;
+    target = n;
     done.store (0, std::memory_order_relaxed);
     ++generation;
     const auto base = generation << (2 * indexBits);
@@ -280,11 +283,36 @@ void WorkerPool::run (int n, void* ctx, Call fn) noexcept
 
     work (false);
 
-    for (int spins = 0; done.load (std::memory_order_acquire) < n; ++spins)
+    // (round 190gq) a short spin for the last indices, then sleep until the worker finishing the round wakes us
+    // (LYNX_CALLER_SLEEP=0: the old spin-and-yield wait, for A/B runs)
+    static const bool callerSleeps = [] { const char* e = std::getenv ("LYNX_CALLER_SLEEP"); return e == nullptr || std::atoi (e) != 0; }();
+    if (! callerSleeps)
+        for (int spins = 0; done.load (std::memory_order_acquire) < n; ++spins)
+        {
+            cpuRelax();
+            if ((spins & 1023) == 1023)
+                std::this_thread::yield();
+        }
+    if (done.load (std::memory_order_acquire) < n)
     {
-        cpuRelax();
-        if ((spins & 1023) == 1023)
-            std::this_thread::yield();
+        const auto spinUntil = std::chrono::steady_clock::now() + std::chrono::microseconds (callerSpinMicros);
+        for (int spins = 0; done.load (std::memory_order_acquire) < n; ++spins)
+        {
+            cpuRelax();
+            if ((spins & 63) == 63 && std::chrono::steady_clock::now() > spinUntil)
+            {
+                callerWaiting.store (true, std::memory_order_seq_cst);
+                if (done.load (std::memory_order_seq_cst) >= n)
+                {
+                    // finished meanwhile: take back the flag, or the wake already sent for it
+                    if (! callerWaiting.exchange (false, std::memory_order_acq_rel))
+                        finished->acquire();
+                    break;
+                }
+                finished->acquire();
+                break;
+            }
+        }
     }
 
     ticket.store (base, std::memory_order_release); // count 0: late workers take nothing

+ 6 - 0
src/core/WorkerPool.h

@@ -112,6 +112,12 @@ private:
     static constexpr int indexBits = 20;
     alignas (64) std::atomic<std::uint64_t> ticket { 0 };
     alignas (64) std::atomic<int> done { 0 };
+    // Round 190gq (REA 190hb: FL's caller never spins): the caller spins callerSpinMicros for the last index, then sleeps
+    // on `finished`; the index that completes the round wakes it (callerWaiting: one wake per wait, never a stale one)
+    std::atomic<bool> callerWaiting { false };
+    int target = 0; // the round's count (written before the ticket)
+    std::unique_ptr<OsSemaphore> finished = std::make_unique<OsSemaphore>();
+    static constexpr int callerSpinMicros = 20;
     alignas (64) std::uint64_t generation = 0; // caller thread only
     std::atomic<std::uint64_t> byWorkers { 0 }, wokenUp { 0 };
     alignas (64) std::atomic<std::uint64_t> workersCpu { 0 };