From cd811ae16a72d3ddbac3b718ad375b5dc14df34c Mon Sep 17 00:00:00 2001 From: Erik Rigtorp Date: Mon, 16 Nov 2026 23:32:04 -0500 Subject: [PATCH] Use cached write index in pop assertion --- include/rigtorp/SPSCQueue.h | 3 ++- src/SPSCQueueTest.cpp | 12 +++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/include/rigtorp/SPSCQueue.h b/include/rigtorp/SPSCQueue.h index 0d1e519..ea3820e 100644 --- a/include/rigtorp/SPSCQueue.h +++ b/include/rigtorp/SPSCQueue.h @@ -202,7 +202,8 @@ class SPSCQueue { /// consumed. Calling pop() on an empty queue violates this precondition. void pop() noexcept { auto const readIdx = readIdx_.load(std::memory_order_relaxed); - assert(writeIdx_.load(std::memory_order_acquire) != readIdx && + // A successful front() has already acquired and cached the write index. + assert(writeIdxCache_ != readIdx && "Can only call pop() after front() has returned a non-nullptr"); std::destroy_at(&slots_[readIdx + kPadding]); auto nextReadIdx = readIdx + 1; diff --git a/src/SPSCQueueTest.cpp b/src/SPSCQueueTest.cpp index 9d861cc..09f941e 100644 --- a/src/SPSCQueueTest.cpp +++ b/src/SPSCQueueTest.cpp @@ -703,7 +703,7 @@ static void testConcurrency() { } } -static void testDeathPopEmpty() { +static void testDeathPopWithoutFront(bool enqueue) { #if (defined(__unix__) || defined(__APPLE__)) && !defined(NDEBUG) using namespace rigtorp; @@ -722,13 +722,18 @@ static void testDeathPopEmpty() { // coredumpctl / ABRT via default SIGABRT termination. std::signal(SIGABRT, [](int) { _exit(42); }); SPSCQueue q(2); - q.pop(); // Must abort in debug builds + if (enqueue) { + q.push(1); + } + q.pop(); // Must abort in debug builds without a successful front() _exit(0); } int status = 0; CHECK(waitpid(pid, &status, 0) == pid); CHECK(WIFEXITED(status) && WEXITSTATUS(status) == 42); +#else + (void)enqueue; #endif } @@ -842,7 +847,8 @@ int main(int argc, char *argv[]) { testAlignedElementPadding(); testCapacityAllocationBounds>(); testCapacityAllocationBounds>(); - testDeathPopEmpty(); + testDeathPopWithoutFront(false); + testDeathPopWithoutFront(true); testTryPop(); testConcurrency();