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

Task graph: a third wait mode, the hand-off: after a bounded spin the waiting position is handed over and the thread that pushes its task runs it at once (round 190kb)

No wake-up on the critical path (Windows: the sleeping waiter of mode 1 doubled the callback's load in parts of Thief).
Tests: the task graph renders bit for bit the same with hand-offs (at once and after a spin).
Ka1-S 2 недель назад
Родитель
Сommit
441c91bbb8
4 измененных файлов с 93 добавлено и 18 удалено
  1. 62 15
      src/core/RackRenderer.cpp
  2. 12 1
      src/core/WorkerPool.cpp
  3. 5 1
      src/core/WorkerPool.h
  4. 14 1
      tests/Spin190kbTests.inc

+ 62 - 15
src/core/RackRenderer.cpp

@@ -5776,28 +5776,66 @@ bool RackRenderer::runTaskGraph (const RackState& state, bool playing, int chann
     graphPushed.store (pushed, std::memory_order_release); // (the pool publishes its work after this: seq_cst)
 
     const auto timing = times->enabled.load (std::memory_order_relaxed);
+    // round 190kb: the wait for a position's task (WorkerPool::Tuning::waitMode): 0 spin with a yield every 1024
+    // pauses (before), 1 bounded spin then sleep until notified, 2 bounded spin then hand the position over — the thread
+    // that pushes its task runs it at once itself (no wake-up on the critical path) and this one goes back to the pool
+    constexpr int handedOver = -1;
+    const auto waitMode = WorkerPool::tuning().waitMode.load (std::memory_order_relaxed);
+    const auto handOffSpin = std::chrono::microseconds (WorkerPool::tuning().waitSpinMicros.load (std::memory_order_relaxed));
     auto task = [&] (int position) {
         const ScopedHostTimeline timelineScope (ownTimeline);
         int id = 0;
-        // (round 190kb: a bounded spin, then sleep until the task pushed into this position wakes it; before, a spin
-        // with a yield every 1024 pauses for as long as it took)
-        workers->await (position, [&] { return (id = graphSlots[(std::size_t) position].load (std::memory_order_acquire)) != 0; });
+        auto& slot = graphSlots[(std::size_t) position];
+        if (waitMode == 2)
+        {
+            if ((id = slot.load (std::memory_order_acquire)) == 0)
+            {
+                const auto start = std::chrono::steady_clock::now();
+                auto handed = false;
+                for (int spins = 0; (id = slot.load (std::memory_order_acquire)) == 0; ++spins)
+                {
+                    WorkerPool::relax();
+                    if ((spins & 63) == 63 && std::chrono::steady_clock::now() - start > handOffSpin)
+                    {
+                        auto expected = 0;
+                        if (slot.compare_exchange_strong (expected, handedOver, std::memory_order_acq_rel))
+                        {
+                            handed = true;
+                            break;
+                        }
+                        id = expected; // (its task came at that moment)
+                        break;
+                    }
+                }
+                workers->noteWait ((std::uint64_t) std::chrono::duration_cast<std::chrono::nanoseconds> (std::chrono::steady_clock::now() - start).count(), handed);
+                if (handed)
+                    return;
+            }
+        }
+        else
+            // (round 190kb: mode 1, a bounded spin, then sleep until the task pushed into this position wakes it)
+            workers->await (position, [&] { return (id = slot.load (std::memory_order_acquire)) != 0; });
         --id;
+        // the tasks of handed-over positions this thread runs (pushed by it); more than fit: run in place, recursively
+        std::array<int, 32> taken;
+        int takenCount = 0;
+        auto chain = [&] (int first, auto& self) -> void {
+            auto at = first;
         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)
+        if (at < channels)
         {
-            renderChannel (state, id, n);
+            renderChannel (state, at, n);
             const auto spent = ProcessTimes::now() - before;
-            if (timing && id < ProcessTimes::channels)
-                times->channelNs[(std::size_t) id].fetch_add (spent, std::memory_order_relaxed);
+            if (timing && at < ProcessTimes::channels)
+                times->channelNs[(std::size_t) at].fetch_add (spent, std::memory_order_relaxed);
             if (measureUnits)
-                channelCostNs[(std::size_t) id] = (std::uint32_t) std::min<std::uint64_t> (spent, 0xffffffffu);
+                channelCostNs[(std::size_t) at] = (std::uint32_t) std::min<std::uint64_t> (spent, 0xffffffffu);
         }
         else
         {
-            const auto t = id - channels + 1;
+            const auto t = at - channels + 1;
             sumChannelsInto (state, t, channels, n);
             if (live)
                 mixLiveInputTrack (state, t, recording, playing, n);
@@ -5807,21 +5845,30 @@ 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;
+        const auto fused = (std::size_t) at < state.graphFused.size() ? state.graphFused[(std::size_t) at] : -1;
         if (fused < 0)
             break;
-        id = fused;
+        at = fused;
         }
-        for (auto k = state.graphNextStart[(std::size_t) id]; k < state.graphNextStart[(std::size_t) id + 1]; ++k)
+        for (auto k = state.graphNextStart[(std::size_t) at]; k < state.graphNextStart[(std::size_t) at + 1]; ++k)
         {
             const auto j = state.graphNext[(std::size_t) k];
             if (graphPending[(std::size_t) j].fetch_sub (1, std::memory_order_acq_rel) == 1)
             {
-                const auto at = graphPushed.fetch_add (1, std::memory_order_acq_rel);
-                graphSlots[(std::size_t) at].store (j + 1, std::memory_order_release);
-                workers->notify (at);
+                const auto pos = graphPushed.fetch_add (1, std::memory_order_acq_rel);
+                auto expected = 0;
+                if (graphSlots[(std::size_t) pos].compare_exchange_strong (expected, j + 1, std::memory_order_acq_rel))
+                    workers->notify (pos);
+                else if (takenCount < (int) taken.size()) // (its thread handed the position over: this one runs it)
+                    taken[(std::size_t) takenCount++] = j;
+                else
+                    self (j, self);
             }
         }
+        };
+        chain (id, chain);
+        while (takenCount > 0)
+            chain (taken[(std::size_t) --takenCount], chain);
     };
     workers->parallelFor (tasks - state.graphFusedCount, task);
 

+ 12 - 1
src/core/WorkerPool.cpp

@@ -182,7 +182,7 @@ void WorkerPool::Tuning::apply (const char* spec) noexcept
     workerSpinMicros.store (std::clamp (parsedValue (spec, "spin", workerSpinMicros.load()), 0, 10000));
     drySpinMicros.store (std::clamp (parsedValue (spec, "dry", drySpinMicros.load()), 0, 10000));
     adaptiveSpin.store (parsedValue (spec, "adaptive", adaptiveSpin.load() ? 1 : 0) != 0);
-    waitMode.store (std::clamp (parsedValue (spec, "wait", waitMode.load()), 0, 1));
+    waitMode.store (std::clamp (parsedValue (spec, "wait", waitMode.load()), 0, 2));
     waitSpinMicros.store (std::clamp (parsedValue (spec, "waitspin", waitSpinMicros.load()), 0, 10000));
 }
 
@@ -273,6 +273,17 @@ void WorkerPool::awaitSlow (int key, void* ready, ReadyFn fn) noexcept
     }
 }
 
+void WorkerPool::noteWait (std::uint64_t ns, bool handedOff) noexcept
+{
+    if (auto* lane = currentLane())
+    {
+        bump (lane->waitNs, ns);
+        bump (lane->waits, 1);
+        if (handedOff)
+            bump (lane->waitSleeps, 1);
+    }
+}
+
 void WorkerPool::notifySlow (int key) noexcept
 {
     for (int k = 0; k < laneCount; ++k)

+ 5 - 1
src/core/WorkerPool.h

@@ -101,7 +101,8 @@ public:
         std::atomic<bool> adaptiveSpin { true };
         std::atomic<int> drySpinMicros { 4 };
         // the waits inside a round for another index's result (await(): the task graph's next task): 0 = spin with a
-        // yield every 1024 pauses (before 190kb), 1 = spin `waitSpinMicros`, then sleep until notify() (no yield)
+        // yield every 1024 pauses (before 190kb), 1 = spin `waitSpinMicros`, then sleep until notify() (no yield),
+        // 2 = (the task graph) spin `waitSpinMicros`, then hand the position over to the thread that will push its task
         std::atomic<int> waitMode { 1 };
         std::atomic<int> waitSpinMicros { 30 };
         void apply (const char* spec) noexcept; // "spin=60,dry=4,adaptive=1,wait=1,waitspin=30" (missing keys: unchanged)
@@ -136,6 +137,9 @@ public:
     }
     // after publishing what await(key, …) waits for: wakes the thread sleeping on that key, if any (a fence and one
     // load when nobody sleeps)
+    // round 190kb: a wait the caller timed itself (the task graph's hand-off): counted as await()'s are, a hand-off as
+    // a sleep
+    void noteWait (std::uint64_t ns, bool handedOff) noexcept;
     void notify (int key) noexcept
     {
         std::atomic_thread_fence (std::memory_order_seq_cst);

+ 14 - 1
tests/Spin190kbTests.inc

@@ -87,7 +87,7 @@ TEST (spin190kb_tuning_parses_specs_and_keeps_missing_keys)
     t.apply ("wait=1"); // the others stay
     CHECK (t.waitMode.load() == 1 && t.workerSpinMicros.load() == 20 && t.waitSpinMicros.load() == 5);
     t.apply ("wait=7,spin=-3,waitspin=99999"); // clamped
-    CHECK (t.waitMode.load() == 1 && t.workerSpinMicros.load() == 0 && t.waitSpinMicros.load() == 10000);
+    CHECK (t.waitMode.load() == 2 && t.workerSpinMicros.load() == 0 && t.waitSpinMicros.load() == 10000);
     t.apply ("nonsense,adaptive=1,,");
     CHECK (t.adaptiveSpin.load());
     t.apply (nullptr);
@@ -143,6 +143,8 @@ TEST (spin190kb_stats_count_rounds_spins_and_sleeps)
     CHECK (after.waits == before.waits); // (no await in these rounds)
 }
 
+static std::uint64_t spin190kbHandOffs = 0;
+
 TEST (spin190kb_task_graph_renders_the_same_in_every_wait_mode)
 {
     // the renderer's task graph with the old wait, the new one (sleeping at once too) and without a pool: bit for bit
@@ -170,6 +172,11 @@ TEST (spin190kb_task_graph_renders_the_same_in_every_wait_mode)
         auto state = lynx::RackState::build (song, nullptr, 48000.0);
         graph = state->graphOk;
         lynx::WorkerPool workers (4);
+        struct Count
+        {
+            lynx::WorkerPool& pool;
+            ~Count() { spin190kbHandOffs += pool.stats().waitSleeps; }
+        } count { workers };
         lynx::RackRenderer r;
         r.prepare (48000.0, 512);
         if (pool)
@@ -190,8 +197,14 @@ TEST (spin190kb_task_graph_renders_the_same_in_every_wait_mode)
     CHECK (graph);
     const auto bounded = render ("wait=1,waitspin=30,adaptive=1", true, unused);
     const auto sleeping = render ("wait=1,waitspin=0,adaptive=1,dry=0", true, unused);
+    // mode 2: the waiting position is handed over to the thread that pushes its task (at once: waitspin=0)
+    const auto handedAtOnce = render ("wait=2,waitspin=0,adaptive=0", true, unused);
+    const auto handedLater = render ("wait=2,waitspin=20,adaptive=1", true, unused);
     CHECK (old == alone);
     CHECK (bounded == alone);
     CHECK (sleeping == alone);
+    CHECK (handedAtOnce == alone);
+    CHECK (handedLater == alone);
+    CHECK (spin190kbHandOffs > 0); // (the hand-offs and sleeps did happen)
     CHECK (*std::max_element (alone.begin(), alone.end()) > 0.02f);
 }