Lab 1: Lock-Free SPSC Worker-to-GUI Sensor Bridge & Coalesced Wakeups

70 minfree previewLinux 6.12← module 1

Enforce the Qt 6 GUI-thread affinity invariant across QThread subclasses and unparented worker QObjects, eliminate cross-thread BlockingQueuedConnection deadlocks, and bridge 10 kHz sensor streams into 60 Hz UI frames using cache-aligned C++20 SPSC atomic rings with coalesced wakeups.

Prerequisites in this module

What ./check.sh verifies

  • Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.
  • Fix compiler warnings or errors in files/core.cpp.
  • Archives core.o into libcore.a and links independent TAP verifier.
  • Preserve public declarations in files/core.hpp so tests.cpp links.
step 1/15

step 1/15 · inspect starter files and specification

High-rate 10 kHz industrial sensors overwhelm Qt's QPostEventList if every sample allocates a QMetaCallEvent. In this studio you repair a cache-aligned C++20 SpscBridge so worker pthreads stream samples across uint32_t wraparound with exact drop accounting and race-free 0 -> 1 coalesced GUI wakeups.

learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01ls -lastarter/Makefilestarter/cli.cppstarter/core.cppstarter/core.hpplearner@ksa:~/gl-q02/lab-m01
starter: starter/Makefile
learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat starter/Makefile File: starter/Makefile    CC_BIN = g++    AR = ar    CFLAGS_ALL = -std=c++20 -Wall -Wextra -Werror -pedantic -O2     LDLIBS = -pthread        all: libcore.a lab_cli        libcore.a: core.o    	$(AR) rcs $@ $^        lab_cli: cli.o libcore.a    	$(CC_BIN) $(CFLAGS_ALL) cli.o libcore.a $(LDLIBS) -o $@        %.o: %.cpp core.hpp    	$(CC_BIN) $(CFLAGS_ALL) -c $< -o $@        .PHONY: all clean    clean:    	rm -f core.o cli.o libcore.a lab_cli
starter: starter/cli.cpp
learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat starter/cli.cpp File: starter/cli.cpp    #include "core.hpp"    #include <algorithm>    #include <array>    #include <cstdint>    #include <cstdio>    #include <cstring>    #include <ctime>        static uint64_t mono_ns() {      struct timespec ts {};      clock_gettime(CLOCK_MONOTONIC, &ts);      return static_cast<uint64_t>(ts.tv_sec) * 1000000000ULL +             static_cast<uint64_t>(ts.tv_nsec);    }        static int run_bench() {      hmi::SpscBridge bridge;      std::array<hmi::SensorSample, 64> out{};      std::array<uint64_t, 40> samples{};      volatile uint64_t sink = 0;          for (int w = 0; w < 5; ++w) {        bool wake = false;        bool rearm = false;        for (uint32_t i = 0; i < 64U; ++i) {          bridge.push({i, static_cast<int32_t>(i), i ^ 0x55U}, &wake);        }        sink += bridge.drainBatch(out.data(), out.size(), &rearm);      }          for (std::size_t s = 0; s < samples.size(); ++s) {        const uint64_t t0 = mono_ns();        for (int rep = 0; rep < 200; ++rep) {          bool wake = false;          bool rearm = false;          for (uint32_t i = 0; i < 64U; ++i) {            bridge.push({i, static_cast<int32_t>(i * 3U), i ^ 0xA5U}, &wake);          }          sink += bridge.drainBatch(out.data(), out.size(), &rearm);        }        samples[s] = (mono_ns() - t0) / 200ULL;      }      std::sort(samples.begin(), samples.end());      std::printf("BENCH lab_m01_worker_spsc_bridge clock=CLOCK_MONOTONIC warmup=5 samples=40 "                  "batch_items=64 p50_ns=%llu p95_ns=%llu p99_ns=%llu sink=%llu\n",                  static_cast<unsigned long long>(samples[20]),                  static_cast<unsigned long long>(samples[38]),                  static_cast<unsigned long long>(samples[39]),                  static_cast<unsigned long long>(sink));      return 0;    }        int main(int argc, char **argv) {      if (argc > 1 && std::strcmp(argv[1], "--bench") == 0) {        return run_bench();      }      hmi::SpscBridge b(0xFFFFFFFCU);      uint32_t wakes = 0;      for (uint32_t i = 0; i < 20U; ++i) {        bool w = false;        b.push({i, static_cast<int32_t>(i * 10U), i ^ 0xCAFEU}, &w);        if (w) ++wakes;      }      std::array<hmi::SensorSample, 8> first{};      std::array<hmi::SensorSample, 16> second{};      bool rearm1 = false;      bool rearm2 = false;      const std::size_t n1 = b.drainBatch(first.data(), first.size(), &rearm1);      const std::size_t n2 = b.drainBatch(second.data(), second.size(), &rearm2);      std::printf("spsc_cli: wakes=%u n1=%zu rearm1=%d n2=%zu rearm2=%d drops=%llu\n",                  wakes, n1, rearm1 ? 1 : 0, n2, rearm2 ? 1 : 0,                  static_cast<unsigned long long>(b.dropCount()));      return (wakes == 1U && n1 == 8U && rearm1 && n2 == 12U && !rearm2) ? 0 : 1;    }
starter: starter/core.cpp
learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat starter/core.cpp File: starter/core.cpp    #include "core.hpp"        namespace hmi {        SpscBridge::SpscBridge(uint32_t initial_idx) noexcept        : write_idx_(initial_idx), read_idx_(initial_idx) {}        bool SpscBridge::push(const SensorSample &sample, bool *should_wake) noexcept {      if (should_wake) {        *should_wake = false;      }      const uint32_t w = write_idx_.load(std::memory_order_relaxed);      const uint32_t r = read_idx_.load(std::memory_order_acquire);      if (w - r == kCapacity - 1U) { // BUG 1: wastes one slot and drops early!        return false; // BUG 1b: forgets to increment drops_!      }      ring_[w & (kCapacity - 1U)] = sample;      write_idx_.store(w + 1U, std::memory_order_release);      notify_pending_.store(true, std::memory_order_relaxed);      if (should_wake) { *should_wake = true; } // BUG 2: wakes on EVERY sample (no 0->1 coalescing)!      return true;    }        std::size_t SpscBridge::drainBatch(SensorSample *out, std::size_t max_batch,                                       bool *rearm_wake) noexcept {      if (rearm_wake) {        *rearm_wake = false;      }      std::size_t count = 0;      uint32_t r = read_idx_.load(std::memory_order_relaxed);      while (count < max_batch) {        const uint32_t w = write_idx_.load(std::memory_order_acquire);        if (r == w) {          break;        }        out[count] = ring_[r & (kCapacity - 1U)];        ++r;        ++count;      }      read_idx_.store(r, std::memory_order_release);      notify_pending_.store(false, std::memory_order_seq_cst);      // BUG 3: missing post-disarm occupancy re-check strands unread items after partial batch!      return count;    }        uint64_t SpscBridge::dropCount() const noexcept {      return drops_.load(std::memory_order_relaxed);    }        uint32_t SpscBridge::sizeApprox() const noexcept {      const uint32_t w = write_idx_.load(std::memory_order_acquire);      const uint32_t r = read_idx_.load(std::memory_order_acquire);      return w - r;    }        } // namespace hmi
starter: starter/core.hpp
learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat starter/core.hpp File: starter/core.hpp    #pragma once    #include <array>    #include <atomic>    #include <cstddef>    #include <cstdint>        namespace hmi {        struct SensorSample {      uint32_t seq = 0;      int32_t value_uv = 0;      uint32_t tag = 0;    };        class SpscBridge {    public:      static constexpr std::size_t kCapacity = 64; // power of two          explicit SpscBridge(uint32_t initial_idx = 0) noexcept;          // Enqueues `sample` if ring is not full. Sets *should_wake = true iff this      // call transitioned notify_pending_ from false -> true (0 -> 1 edge).      // On full ring (w - r == kCapacity), increments drops_ and returns false.      bool push(const SensorSample &sample, bool *should_wake) noexcept;          // Pops up to `max_batch` samples into `out[]`. Disarms notify_pending_ and      // sets *rearm_wake = true iff unread samples remain and caller re-armed 0 -> 1.      std::size_t drainBatch(SensorSample *out, std::size_t max_batch,                             bool *rearm_wake) noexcept;          uint64_t dropCount() const noexcept;      uint32_t sizeApprox() const noexcept;        private:      alignas(64) std::atomic<uint32_t> write_idx_;      alignas(64) std::atomic<uint32_t> read_idx_;      alignas(64) std::atomic<bool> notify_pending_{false};      std::atomic<uint64_t> drops_{0};      std::array<SensorSample, kCapacity> ring_{};    };        } // namespace hmi

step 2/15 · 2. learning objectives

  • Enforce full power-of-two capacity (w - r == kCapacity), unsigned 32-bit wraparound, and exact drops_ accounting.
  • Coalesce worker-to-GUI notifications on the false -> true notify_pending_ edge via exchange(true, acq_rel).
  • Close the post-batch lost-wakeup race by disarming notify_pending_ with seq_cst and re-testing write_idx_ != r.

step 3/15 · 3. environment requirements

All automated verification steps run in unprivileged user space on a POSIX Linux host using g++ -std=c++20 -Wall -Wextra -Werror -pedantic and clock_gettime(CLOCK_MONOTONIC). Recorded transcripts in captures.json were generated on x86_64 running kernel 7.0.0-42-generic and prove protocol, state-machine, and memory invariants only. Physical bus timing, DMA cache coherency, and board peripheral behavior require target validation on Linux kernel 6.12 LTS (ARMv7-A Cortex-A7).

step 4/15 · 4. required software and hardware

  • Host workstation: g++ (-std=c++20 -Wall -Wextra -Werror -pedantic), GNU make, ar (binutils), and POSIX /bin/sh.
  • Target environment (optional hardware step, Section 13): Dual-core or single-core ARMv7-A Cortex-A7 running Linux kernel 6.12 LTS and Qt 6.8 (Wayland or eglfs_kms) streaming SPI IMU samples into a 60 Hz plot widget.

step 5/15 · 5. complete executable commands

learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat script.sh File: script.sh    make -B -C files    ./files/lab_cli    ./files/lab_cli --bench    sh check.sh

step 6/15 · 6. annotated source code

files/core.cpp enforces the production invariants that starter/core.cpp breaks:

learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat example.cpp File: example.cpp    ring_[w & (kCapacity - 1U)] = sample;    write_idx_.store(w + 1U, std::memory_order_release);    const bool prev = notify_pending_.exchange(true, std::memory_order_acq_rel);    if (!prev && should_wake) *should_wake = true;    ...    notify_pending_.store(false, std::memory_order_seq_cst);    if (write_idx_.load(std::memory_order_seq_cst) != r) {      if (!notify_pending_.exchange(true, std::memory_order_acq_rel) && rearm_wake) {        *rearm_wake = true;      }    }

starter/core.cpp injects three realistic concurrency bugs: (1) push() tests kCapacity - 1U and omits drops_.fetch_add(1U); (2) push() sets *should_wake = true unconditionally on every sample instead of checking !notify_pending_.exchange(true); and (3) drainBatch() omits the post-disarm write_idx_ != r re-arm check.

step 7/15 · 7. expected output

Passing files/ run (sh check.sh, exit code 0):

learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat listing.txt File: listing.txt    TAP version 13    1..5    ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic    ok 2 - archives core.o into libcore.a and links independent TAP verifier    ok 3 - preserves full kCapacity=64 slots, dropCount accounting, and uint32_t wraparound    ok 4 - coalesces 0->1 notify_pending wakeups and re-arms after bounded batch drain    ok 5 - transfers 20000 concurrent jthread samples across wraparound with zero corruption    # pass 5/5

CLI verification output (./files/lab_cli):

learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat listing.txt File: listing.txt    spsc_cli: wakes=1 n1=8 rearm1=1 n2=12 rearm2=0 drops=0

Defective starter/ run (exit code 1): emits FAIL: diagnostics on the broken contract assertions.

step 8/15 · 8. explanation of observed behavior

Once all three invariants are restored in files/core.cpp, sh check.sh builds libcore.a with -std=c++20 -Wall -Wextra -Werror -pedantic -O2 -pthread and passes all 5/5 TAP version 13 checks including the two-thread 20,000-sample wraparound stress run.

step 9/15 · 9. experiment variations

  • Near transfer: Add a highWaterMark() atomic counter to SpscBridge updated via std::max on w - r during push() so an operator diagnostics screen can warn at 80% ring occupancy.
  • Far transfer: Wrap SpscBridge in a template header wired to QMetaObject::invokeMethod(gui, slot, Qt::QueuedConnection) and measure frame-time p99 jitter at 20 kHz vs per-sample signals.

step 10/15 · 10. performance measurements

Recorded host benchmark (./files/lab_cli --bench, CLOCK_MONOTONIC, warmup=5, N=40 batches):

learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat listing.txt File: listing.txt    BENCH lab_m01_worker_spsc_bridge clock=CLOCK_MONOTONIC warmup=5 samples=40 batch_items=64 p50_ns=1081 p95_ns=1145 p99_ns=1247 sink=512320

The ./files/lab_cli --bench CLOCK_MONOTONIC percentiles measure single-process user-space 64-sample push+drain ring throughput on the host CPU. Do not extrapolate host L1 cache timings to ARMv7-A cross-core DMB ISH latency or physical SPI DMA interrupt jitter.

step 11/15 · 11. troubleshooting

SymptomRoot causeFix
not ok 3 - preserves full kCapacity=64 slots...push() rejects at kCapacity - 1U or forgets drops_.fetch_add(1U, relaxed).Compare if (w - r == kCapacity) and increment drops_ before returning false.
not ok 4 - coalesces 0->1 notify_pending wakeups...notify_pending_.exchange(true) is missing or drainBatch() fails to re-arm when w != r.Set *should_wake = !notify_pending_.exchange(true, acq_rel) and re-check write_idx_ != r after storing false.
not ok 5 - transfers 20000 concurrent jthread samples...Missing re-arm hangs consumer when max_batch=32 leaves items unread in the ring.Restore seq_cst disarm + write_idx_.load(seq_cst) != r re-arm block at the end of drainBatch().

step 12/15 · 12. guided questions

  1. Why can SpscBridge::push() load write_idx_ with std::memory_order_relaxed while loading read_idx_ requires std::memory_order_acquire?
  • *Hint 1:* Which thread is the sole writer of write_idx_, and which thread writes read_idx_ after reading ring_[r & MASK]?
  • *Hint 2:* Only the producer writes write_idx_ (so it already sees its own latest store), whereas acquiring read_idx_ ensures the consumer finished reading the old slot before the producer overwrites it!
  1. Why do write_idx_, read_idx_, and notify_pending_ each carry alignas(64) in core.hpp?
  • *Hint 1:* What happens in the MESI cache coherency protocol when two cores atomically store into adjacent 4-byte integers inside the same 64-byte L1 cache line?
  • *Hint 2:* Without alignas(64), every producer write_idx_ increment invalidates the consumer's read_idx_ cache line across cores (false sharing), multiplying bus coherence traffic.

step 13/15 · 13. independent challenges

Extend SpscBridge with a zero-copy tryAcquireWriteSlot() / commitWriteSlot() span API so a read(fd, ...) syscall writes sensor bytes directly into ring_[w & MASK] without an intermediate stack copy.

step 14/15 · 14. solutions and explanations

files/core.cpp checks w - r == kCapacity with unsigned wraparound, publishes w + 1U via memory_order_release, gates wakeups on !notify_pending_.exchange(true, acq_rel), and re-tests write_idx_.load(seq_cst) != r immediately after notify_pending_.store(false, seq_cst).

step 15/15 · run verification and inspect output

Run the verification command and confirm the output matches the expected contract.

learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01./files/lab_clilearner@ksa:~/gl-q02/lab-m01
expected output
spsc_cli: wakes=1 n1=8 rearm1=1 n2=12 rearm2=0 drops=0

Progressive hints & solution

hint 1

Compare starter/Makefile against the module lessons. Focus first on: Builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic.

hint 2

Compile with -std=c11 -Wall -Wextra -Werror, check every system-call return value before touching output buffers, and verify cleanup on error paths.

solution

Run the check

From labs/lab_m01_worker_spsc_bridge/, run ./check.sh. A complete solution emits TAP version 13 with every test point marked ok and exits 0:

./check.sh — lab m01
learner@ksa:~/gl-q02/lab-m01./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifierok 3 - preserves full kCapacity=64 slots, dropCount accounting, and uint32_t wraparoundok 4 - coalesces 0->1 notify_pending wakeups and re-arms after bounded batch drainok 5 - transfers 20000 concurrent jthread samples across wraparound with zero corruption# pass 5/5

On an incomplete starter tree, ./check.sh exits non-zero and marks the unmet assertion not ok with an indented YAML diagnostic block:

./check.sh — lab m01 (starter)
learner@ksa:~/gl-q02/lab-m01./check.shTAP version 131..5ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedanticok 2 - archives core.o into libcore.a and links independent TAP verifiernot ok 3 - preserves full kCapacity=64 slots, dropCount accounting, and uint32_t wraparoundFAIL: check w - r == kCapacity and increment drops_ before returning false in SpscBridge::push  ---  message: 'got premature full at i=63'  hint: 'check w - r == kCapacity and increment drops_ before returning false in SpscBridge::push'  ...not ok 4 - coalesces 0->1 notify_pending wakeups and re-arms after bounded batch drainFAIL: use notify_pending_.exchange(true, acq_rel) in push and re-check write_idx_ != r after disarming in drainBatch  ---  message: 'got expected 1 coalesced wakeup, got 20'  hint: 'use notify_pending_.exchange(true, acq_rel) in push and re-check write_idx_ != r after disarming in drainBatch'  ...not ok 5 - transfers 20000 concurrent jthread samples across wraparound with zero corruptionFAIL: publish write_idx_ with memory_order_release and load with memory_order_acquire across threads  ---  message: 'got build_failed'  hint: 'publish write_idx_ with memory_order_release and load with memory_order_acquire across threads'  ...# pass 2/5

note: How to read TAP diagnostics: 1..N states the total test plan; each ok k confirms a passed check; not ok k pinpoints the failing check alongside message: (what went wrong) and hint: (where to look next) between --- and ....

inspect harness: check.sh
learner@ksa: ~/gl-q02/lab-m01
learner@ksa:~/gl-q02/lab-m01$ bat check.sh File: check.sh    #!/bin/sh    set -u    cd "$(dirname "$0")" || exit 1    PASS=0    WORK=$(mktemp -d "${TMPDIR:-/tmp}/ksa_lab.XXXXXX") || exit 1    trap 'rm -rf "$WORK"' EXIT HUP INT TERM    cp -R files "$WORK/files"        printf 'TAP version 13\n1..5\n'    if make -B -C "$WORK/files" >"$WORK/build.log" 2>&1; then        printf 'ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n'        PASS=$((PASS + 1))    else        printf 'not ok 1 - builds libcore.a and lab_cli cleanly with -std=c++20 -Wall -Wextra -Werror -pedantic\n'        printf 'FAIL: fix compiler warnings or errors in files/core.cpp\n'    fi        if [ -f "$WORK/files/libcore.a" ] && g++ -std=c++20 -Wall -Wextra -Werror -pedantic -O2  -I"$WORK/files" tests.cpp "$WORK/files/libcore.a" -pthread -o "$WORK/verify" >>"$WORK/build.log" 2>&1; then        printf 'ok 2 - archives core.o into libcore.a and links independent TAP verifier\n'        PASS=$((PASS + 1))    else        printf 'not ok 2 - archives core.o into libcore.a and links independent TAP verifier\n'        printf 'FAIL: preserve public declarations in files/core.hpp so tests.cpp links\n'    fi        if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 1 2>&1); then        printf 'ok 3 - preserves full kCapacity=64 slots, dropCount accounting, and uint32_t wraparound\n'        PASS=$((PASS + 1))    else        printf 'not ok 3 - preserves full kCapacity=64 slots, dropCount accounting, and uint32_t wraparound\n'        printf 'FAIL: check w - r == kCapacity and increment drops_ before returning false in SpscBridge::push\n'        printf "  ---\n  message: 'got %s'\n  hint: 'check w - r == kCapacity and increment drops_ before returning false in SpscBridge::push'\n  ...\n" "${OUT:-build_failed}"    fi        if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 2 2>&1); then        printf 'ok 4 - coalesces 0->1 notify_pending wakeups and re-arms after bounded batch drain\n'        PASS=$((PASS + 1))    else        printf 'not ok 4 - coalesces 0->1 notify_pending wakeups and re-arms after bounded batch drain\n'        printf 'FAIL: use notify_pending_.exchange(true, acq_rel) in push and re-check write_idx_ != r after disarming in drainBatch\n'        printf "  ---\n  message: 'got %s'\n  hint: 'use notify_pending_.exchange(true, acq_rel) in push and re-check write_idx_ != r after disarming in drainBatch'\n  ...\n" "${OUT:-build_failed}"    fi        if [ -x "$WORK/verify" ] && OUT=$("$WORK/verify" 3 2>&1); then        printf 'ok 5 - transfers 20000 concurrent jthread samples across wraparound with zero corruption\n'        PASS=$((PASS + 1))    else        printf 'not ok 5 - transfers 20000 concurrent jthread samples across wraparound with zero corruption\n'        printf 'FAIL: publish write_idx_ with memory_order_release and load with memory_order_acquire across threads\n'        printf "  ---\n  message: 'got %s'\n  hint: 'publish write_idx_ with memory_order_release and load with memory_order_acquire across threads'\n  ...\n" "${OUT:-build_failed}"    fi    printf '# pass %d/5\n' "$PASS"    [ "$PASS" -eq 5 ]

Definition of done

Verification checklist

status: 0/3 checks verified

Troubleshooting

Compiler fails under -Werror on sign conversion or unused args

Use exact POSIX return types (ssize_t for read()/write(), size_t for byte counts) rather than relaxing flags.

./check.sh reports missing files in files/

Invoke ./check.sh from inside labs/lab_m01_worker_spsc_bridge/ so relative paths to files/ resolve directly.

Progress is saved on this device.

search — fzf

0/0 ───────────────────────────────────────────

keyboard shortcuts — less

/
search
f
focus mode
[
previous
]
next
?
help
Esc
close

figure