Testing concurrent code and its limits
What you will learn on this page
Section titled “What you will learn on this page”- Why tests of concurrent code are hard to trust: the order in which threads run changes from run to run, and most orders are never tried.
- Two design choices that make a shared class testable: a seam for waiting, so a test can decide what other threads do while one waits, and a report of who is waiting, so a test can wait for a state instead of for time.
- How to write scripted tests that play out one interleaving of threads, the same way on every run, in a single thread.
- How to write tests with real threads that are not flaky, and why their checks belong on the test’s own thread.
- What a stress test finds, and why, when it finds something, it often says little about where.
- What ThreadSanitizer finds, and what it cannot.
- Why a passing test run, of any kind, does not prove concurrent code correct, and what else to lean on.
The problem: a queue between threads
Section titled “The problem: a queue between threads”A service writes log lines from several threads. Sending each line over the network as it is written would make every writer wait for the network, so the writers put lines into a queue, and one shipper thread takes them off and sends them in batches. The queue has room for a fixed number of lines; when it is full, a writer waits. That wait is the backpressure the backpressure page describes: a slow network slows the writers down instead of filling memory.
The queue’s requirements:
- Q1.
pushwaits while the queue is full. - Q2.
popwaits while the queue is empty. - Q3.
closewakes every waiting thread. After it,pushrefuses its item and returnsfalse;popstill returns the items already queued, thenstd::nullopt. - Q4. No item is lost or delivered twice, and the items from one producer come out in the order that producer pushed them.
The last requirement is the one that matters most to the people reading the logs, and it is the hardest to test, because it is about every possible order in which the threads might run.
The queue’s interface, with the two additions this page is about:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A snapshot of the queue, taken under its lock: how many items it holds,// and how many threads are blocked in it right now. A test reads it to know,// not guess, that a thread is waiting. By the time the caller looks, the// real queue may already have moved on; the snapshot was true when taken.struct QueueStats { std::size_t size = 0; std::size_t waiting_producers = 0; // blocked in push(): the queue is full std::size_t waiting_consumers = 0; // blocked in pop(): the queue is empty};
// Thread safety: safe, for any number of producers and consumers.// push() waits while the queue is full, and returns false, dropping the// item, if the queue is closed. pop() waits while the queue is empty, and// returns std::nullopt only once it is closed and empty.//// CondVar is std::condition_variable, except in tests. It must offer// wait(lock, ready), notify_one(), and notify_all(), and be constructible// from the constructor's `cond_var_args`.//// T is the item type. `= std::condition_variable` is a default template// argument: BoundedQueue<std::string> uses the real one, and only a test// writes the second argument.template <typename T, typename CondVar = std::condition_variable>class BoundedQueue { // Refuses, at compile time, an item type whose move can throw. Items // are moved in and out of the queue; once pop() has removed an item, a // move that threw on the way out would lose it. static_assert(std::is_nothrow_move_constructible_v<T>);
public: // capacity: the most items the queue holds; throws std::invalid_argument // for 0, since a queue with no room could never accept a push. // `typename... CondVarArgs` is a parameter pack: any number of extra // arguments, of any types, taken by reference. The same arguments are // given to both condition variables. std::condition_variable takes // none, so ordinary code passes none; a test passes its Script, so both // scripted condition variables share one script. template <typename... CondVarArgs> explicit BoundedQueue(std::size_t capacity, CondVarArgs&... cond_var_args) : not_full_(cond_var_args...), not_empty_(cond_var_args...), capacity_(capacity) { if (capacity == 0) { throw std::invalid_argument("a bounded queue needs room for one item"); } }
// Not copyable: a mutex and condition variables cannot be copied, and // a copy of a queue that threads are blocked in would mean nothing. BoundedQueue(const BoundedQueue&) = delete; BoundedQueue& operator=(const BoundedQueue&) = delete;
[[nodiscard]] bool push(T item); std::optional<T> pop(); void close(); // wakes every waiting thread; queued items can still be popped [[nodiscard]] QueueStats stats() const;
private: // Counts the calling thread as waiting for as long as it exists. // An RAII guard: the constructor adds one to the count it is given and // the destructor takes one away, so the count goes back down however // the wait ends, even by an exception. It holds a reference to the // count, not a copy, and is created and destroyed while mutex_ is held, // which is what makes the plain size_t safe to change. class Waiting { public: explicit Waiting(std::size_t& count) noexcept : count_(count) { ++count_; } ~Waiting() { --count_; } Waiting(const Waiting&) = delete; Waiting& operator=(const Waiting&) = delete;
private: std::size_t& count_; };
// One mutex guards all the state below. `mutable` lets stats(), a const // function, still lock it: locking does not change what the queue holds. mutable std::mutex mutex_; CondVar not_full_; // producers wait here CondVar not_empty_; // consumers wait here std::deque<T> items_; // guarded by mutex_ bool closed_ = false; // guarded by mutex_ std::size_t waiting_producers_ = 0; // guarded by mutex_ std::size_t waiting_consumers_ = 0; // guarded by mutex_ const std::size_t capacity_; // never changes, so needs no lock};And its two operations. Each waits in a loop on its own condition variable, as the backpressure page explains, and notifies after letting go of the lock:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Adds an item, waiting while the queue is full. Returns true once the item// is queued, or false, without queuing it, if the queue is or becomes closed.// The item is taken by value, so the caller can move it in.template <typename T, typename CondVar>bool BoundedQueue<T, CondVar>::push(T item) { // The extra braces are a scope for the lock: it is released at the // closing brace, before the notify below. { // unique_lock (not scoped_lock) because wait() must be able to let // go of the lock while it waits and take it back before returning. std::unique_lock lock(mutex_); if (!closed_ && items_.size() == capacity_) { // Counted as a waiting producer from here to the end of this if. const Waiting waiting(waiting_producers_); // wait(lock, ready) first checks ready(); while it is false, it // releases the lock, sleeps until notified, takes the lock back, // and checks again. So a spurious wakeup or a slot taken by another // producer just means waiting again. The lambda captures `this` // to read the members. It returns with the lock held. not_full_.wait(lock, [this] { return closed_ || items_.size() < capacity_; }); } // Either way, the lock is held here, and the queue is closed or has // room. A closed queue refuses the item, even if there is room. if (closed_) { return false; } items_.push_back(std::move(item)); } // Wake one consumer that may be waiting for an item. This is done after // the lock is released, so the woken thread does not wake only to find // the mutex still held. not_empty_.notify_one(); return true;}
// Takes the oldest item, waiting while the queue is empty. Returns// std::nullopt only when the queue is closed and has no items left; items// queued before close() are still handed out first.template <typename T, typename CondVar>std::optional<T> BoundedQueue<T, CondVar>::pop() { // Declared outside the lock's scope so it survives it; empty for now. std::optional<T> item; { std::unique_lock lock(mutex_); if (!closed_ && items_.empty()) { const Waiting waiting(waiting_consumers_); // Same loop as in push: wakes only to a closed queue or an item. not_empty_.wait(lock, [this] { return closed_ || !items_.empty(); }); } // Lock held; there is an item, or the queue is closed. Checking for // items first is what lets a closed queue still be drained. if (items_.empty()) { return std::nullopt; // closed, and every item has been taken } // Move the front item into `item`, then remove the moved-from // element from the deque. front() must be read before pop_front(), // which destroys it. item.emplace(std::move(items_.front())); items_.pop_front(); } // A slot is free now: wake one producer that may be waiting for room. not_full_.notify_one(); return item;}How this code works: push and pop, step by step
Both functions have the same four parts. Here is push; pop is the
mirror image, with “empty” for “full” and not_empty_ for not_full_.
- Take the lock.
std::unique_lock lock(mutex_)locks the mutex. From here until the inner block’s closing brace, no other thread can read or changeitems_orclosed_, except while the wait in step 2 has let go of the lock. - Wait, only if there is a reason to. If the queue is open and
full, the producer is counted by a
Waitingguard and callsnot_full_.wait(lock, ready). That call lets go of the lock while it sleeps, which is what lets a consumer get in and take an item, and it has the lock again whenever it checksreadyor returns. It returns only once the queue is closed or has room. A wakeup that finds neither, because another producer filled the slot first or nobody notified at all, just waits again. When theifblock ends, the guard is destroyed and the count goes back down, still under the lock. - Decide, still holding the lock. A closed queue refuses the item
and returns
false;lockis released as the function returns. Otherwise the item is moved into the back of the deque. - Release, then notify. The inner block ends, so
lockis destroyed and the mutex is free. Only then doesnotify_onewake one consumer that may be waiting, which can take the lock at once.
pop makes one choice differently in step 3: it checks for an item
before it looks at closed_. A closed queue that still holds items
hands them out, and only a closed and empty queue gives
std::nullopt, which is requirement Q3.
Where the item lives. push receives its own copy of the item (or
the caller’s, moved in), moves it into the deque, and the deque owns it
while it is queued. pop moves it from the front of the deque into the
local std::optional, removes the moved-from element, and returns the
optional to the caller. The static_assert at the top of the class
refuses item types whose move could throw, so this last step cannot
fail after the item has left the queue.
The demo has three writer threads push 100 lines each through a queue with room for 8, while a shipper thread pops them. It prints only a summary, so its output is the same however the threads ran:
shipped 300 of 300 lines from 3 sourceseach source's lines arrived in order: yesWhy concurrent tests are hard to trust
Section titled “Why concurrent tests are hard to trust”A test of single-threaded code runs the same instructions in the same order every time. A test with threads does not. Each run, the operating system decides when each thread runs and for how long, and those decisions depend on the load on the machine, the number of cores, and timing nobody controls. Each possible order is an interleaving. Three problems follow:
- A bug may live in a rare interleaving. If a consumer can fail only when another consumer takes an item in the few microseconds between a notify and the moment the first consumer wakes, a test may run thousands of times without that happening, or make it happen often, but never on demand, at a chosen point.
- A test that waits for time is slow, and still not sure. The thread safety and backpressure pages each have a test that sleeps so that another thread is “probably” waiting by the time it goes on. Both pages say it plainly: the sleep makes that likely, not certain. Make the sleep longer and the test gets slower; make it shorter and it more often tests something other than what it says.
- A failure may not repeat. A test that fails once in a hundred runs is a flaky test. People learn to rerun it, and then a real bug that fails once in a hundred runs is rerun too.
The way out is not cleverer sleeping. It is to change the design so that a test can decide, or at least see, what the threads are doing.
Design for determinism
Section titled “Design for determinism”The queue has two features that exist mainly for its tests. Both are cheap, and both are worth asking about before adding them to your own code.
The condition variable is a template parameter. BoundedQueue<T>
uses std::condition_variable, so production code is unchanged:
BoundedQueue<std::string> queue(8) is how the demo builds one. A test
can name a different type, BoundedQueue<int, ScriptedCondVar>, whose
wait does not block at all, and instead runs steps the test wrote,
as if other threads ran them while this one waited. This is a
seam, in the sense of the test doubles page: a place where a test
can put something else, here chosen at compile time. The constructor
passes any extra arguments on to both condition variables, which is
how the scripted one gets its script; std::condition_variable takes
none, so ordinary code passes none.
The queue counts the threads waiting in it. stats() reports how
many producers are blocked in push and how many consumers in pop.
A test with real threads can wait until a producer is counted as
waiting, and then know, rather than hope, that it is blocked. The
count is kept by a small private RAII class, Waiting, which adds one
when it is created and takes one away when it is destroyed, so a wait
that ends by an exception is still uncounted.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Takes the lock like every other reader, so the three numbers are read// together and none is read while another thread is changing it.// scoped_lock is enough here: nothing waits, so the lock is simply held// until the function returns. The braces build a QueueStats from the three// values, in the order its members are declared.template <typename T, typename CondVar>QueueStats BoundedQueue<T, CondVar>::stats() const { const std::scoped_lock lock(mutex_); return {items_.size(), waiting_producers_, waiting_consumers_};}stats() takes the lock, like every other member that reads the
queue’s state. Later on this page, a copy of the queue that skips the
lock here shows what that costs.
Scripted tests: one interleaving per test
Section titled “Scripted tests: one interleaving per test”Here is the stand-in condition variable. Its wait lets go of the lock,
as a real wait does, and then runs the next steps of a Script, in
order, in the same thread, until a step notifies it. Then it takes the
lock back and returns. If the script runs out while it is still waiting,
nothing will ever wake it, which with real threads would be a hang; here
it throws BlockedForever instead, so the test fails, or checks for it.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Thrown when a thread waits and nothing left in the script will wake it.// With real threads, that thread would hang.struct BlockedForever : std::runtime_error { BlockedForever() : std::runtime_error("a thread waits, and nothing will ever wake it") {}};
// What the other threads do, in order, while a thread waits. A test fills// it with steps before calling the queue; each wait then uses up steps from// the front. Both condition variables of a queue share one Script.class Script {public: // Another thread runs `step`. A step must not wait itself. // std::function<void()> holds any callable taking nothing, here usually // a lambda; it is moved into the list rather than copied. void then(std::function<void()> step) { steps_.push_back(std::move(step)); } // The waiting thread wakes without being notified, as the standard allows. // An empty std::function (nullptr) is the marker for "wake up now". void then_spurious_wakeup() { steps_.push_back(nullptr); } // True once every step has run: a test checks it to prove that the // interleaving it describes really happened. [[nodiscard]] bool finished() const noexcept { return steps_.empty(); }
private: // The condition variable may read and change the private members below. friend class ScriptedCondVar; std::deque<std::function<void()>> steps_; // True while some thread is inside a wait. Kept here, not in each // condition variable, so a step that waits on either one is caught. bool waiting_ = false;};
// wait() never blocks. It lets go of the lock and runs the script's steps,// as if other threads ran them, until a step notifies this condition// variable or the script says to wake up spuriously; then it takes the// lock back. There is only ever one waiting thread, so notify_one and// notify_all both wake it.class ScriptedCondVar {public: // Keeps a pointer to the script, not a copy, so the script must outlive // the queue. A test declares the Script first for that reason. explicit ScriptedCondVar(Script& script) noexcept : script_(&script) {}
// One wait, as a real wait(lock) would do it, but in this thread: called // with the lock held, returns with the lock held, and in between runs // steps with the lock released. Throws BlockedForever if the steps run // out first, and std::logic_error if a step itself tries to wait, since // the script models only one waiting thread at a time. void wait(std::unique_lock<std::mutex>& lock) { if (script_->waiting_) throw std::logic_error("a script step must not wait"); notified_ = false; // a notify from before the wait is lost, as with the real one script_->waiting_ = true; // Let go of the lock, as a real wait does, so that the steps can // call the queue's members, which take the lock themselves. lock.unlock(); // However the wait ends, even by a step throwing, it ends as a real // wait does: with the lock held again. const Relock relock{*script_, lock}; // Run steps until one of them notifies this condition variable. A // notify is noticed only when the step that made it has finished, so // one step can push an item and also take it before the waiter wakes. while (!notified_) { if (script_->steps_.empty()) throw BlockedForever(); // Take the next step out of the script, so that it runs once and // the next wait starts from the step after it. const std::function<void()> step = std::move(script_->steps_.front()); script_->steps_.pop_front(); if (!step) break; // a spurious wakeup step(); } }
// The loop the standard specifies for std::condition_variable's // wait(lock, ready). // Ready is the type of whatever callable the queue passes, here its // lambda. Waiting again after every wakeup until ready() is true is what // makes a spurious wakeup or a stolen item harmless. template <typename Ready> void wait(std::unique_lock<std::mutex>& lock, Ready ready) { while (!ready()) wait(lock); }
// A notify only sets a flag that the waiting loop above reads. Each // condition variable has its own flag, so notifying not_full_ does not // wake a consumer waiting on not_empty_. void notify_one() noexcept { notified_ = true; } void notify_all() noexcept { notified_ = true; }
private: // An RAII guard for the end of a wait. Its destructor runs when wait() // returns or when an exception leaves it, and either way marks the // thread as no longer waiting and takes the lock back. struct Relock { Script& script; std::unique_lock<std::mutex>& lock; ~Relock() { script.waiting_ = false; lock.lock(); } };
Script* script_; bool notified_ = false;};How this code works: ScriptedCondVar::wait
The queue calls wait(lock, ready), which loops: while ready() is
false, it calls the one-argument wait(lock). One call of that inner
wait does this, all in the test’s own thread:
- Refuse a nested wait. If the script is already marked as
waiting, a step has called something that waits, which this
stand-in cannot play out, so it throws
std::logic_error. - Forget old notifies.
notified_ = false. A notify made before the wait started is lost, as it would be with a real condition variable. - Let go of the lock and mark the script as waiting. Now steps can call the queue, which takes the same lock.
- Arrange to take the lock back. The
Relockguard’s destructor relocks and clears the waiting mark. It runs howeverwaitends: by returning, or by an exception from a step or fromBlockedForever. - Run steps until a notify. Each turn of the loop takes the next
step off the front of the script. If there is none, nothing will
ever wake this thread, so it throws
BlockedForever. An empty step is a spurious wakeup: leave the loop without a notify. Otherwise run the step. If the step callednotify_oneornotify_allon this condition variable,notified_is now true and the loop ends. - Return with the lock held (the
Relockdestructor), and the outer loop checksready()again.
Because notified_ is checked only between steps, a single step can
notify and then undo the reason for the notify before the waiter looks.
That is how the next tests put another thread’s action between a
notify and the moment the waiter has the lock again.
Each step stands for something another thread does. A step runs while
the waiting thread has let go of the lock, so a step can call the
queue’s members, which take the lock themselves. The script also
offers a spurious wakeup, a return from wait that nobody asked
for, which the standard allows a real condition variable to do at any
time. A real one rarely does, so a real test almost never sees it;
a script can produce one on demand.
The first tests check Q1 and Q2: that a thread waits when it should, and wakes when it should.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// TestQueue is BoundedQueue<int, ScriptedCondVar>: a queue of int whose// waits run the script instead of blocking. LLD_TEST(name) defines a test;// LLD_CHECK(condition) records a failure if the condition is false;// LLD_CHECK_EQ(actual, expected) compares with == and prints both values on// a failure; LLD_CHECK_THROWS(expression, type) fails unless the expression// throws that type. They come from the site's test header, lld_test.hpp.//// An empty queue makes pop() wait, and with no steps, nothing can wake it.LLD_TEST(a_consumer_waits_while_the_queue_is_empty) { Script script; // nothing else happens // Room for 2 items. `script` is passed on to both condition variables. TestQueue queue(2, script); LLD_CHECK_THROWS(queue.pop(), BlockedForever); // 0u is 0 as an unsigned number, the same kind as the size_t count. LLD_CHECK_EQ(queue.stats().waiting_consumers, 0u); // no longer counted once it gave up}
LLD_TEST(a_consumer_wakes_when_an_item_is_pushed) { Script script; TestQueue queue(2, script); // The step is written now and runs later, inside pop()'s wait, while // the lock is released. [&] lets it use `queue` by reference. script.then([&] { LLD_CHECK(queue.push(1)); }); // pop() returns std::optional<int>; comparing it with 1 is true only // if it holds 1. LLD_CHECK(queue.pop() == 1); LLD_CHECK(script.finished());}
LLD_TEST(a_producer_waits_while_the_queue_is_full_until_an_item_is_taken) { Script script; // Room for one item, so the first push fills it. TestQueue queue(1, script); LLD_CHECK(queue.push(1)); script.then([&] { LLD_CHECK(queue.pop() == 1); }); // Full, so push(2) waits; the step takes 1, which makes room and // notifies not_full_, and push(2) then queues its item. LLD_CHECK(queue.push(2)); // Full again, with no steps left: the wait cannot end. push is // [[nodiscard]], hence the cast to void. LLD_CHECK_THROWS(static_cast<void>(queue.push(3)), BlockedForever); // nobody pops again // push(3) left by the exception, so 3 was never queued; 2 is still the only item. LLD_CHECK(queue.pop() == 2);}- A consumer on an empty queue waits. With nothing in the script,
popthrowsBlockedForever: it waited, and nothing came. The waiting count is back to 0 afterwards, becauseWaitingwas destroyed as the exception leftpop. - A push wakes it. The script’s one step pushes 1, which notifies
the consumer, and
popreturns 1.script.finished()checks that every step ran, so a test cannot pass by accident without the interleaving it describes. - A full queue makes a producer wait until a step takes an item.
The third push,
push(3), then has nobody left to make room, and throws.
The checks inside steps run on the test’s thread, like the rest of a scripted test, so they are safe; that will matter when real threads appear.
The next tests are the reason for scripting. Each plays out an interleaving that a test with real threads may or may not produce, and never at a chosen point on every run:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Between the notify and the moment the woken consumer has the lock// again, another consumer that was not waiting takes the item.LLD_TEST(a_consumer_that_loses_the_item_to_another_waits_again) { Script script; TestQueue queue(2, script); script.then([&] { LLD_CHECK(queue.push(1)); // a producer pushes, and notifies LLD_CHECK(queue.pop() == 1); // another consumer takes it first }); // Only reached if pop() waits again after losing the 1. script.then([&] { LLD_CHECK(queue.push(2)); }); LLD_CHECK(queue.pop() == 2);}
LLD_TEST(a_spurious_wakeup_is_not_taken_for_an_item) { Script script; TestQueue queue(2, script); // pop() is woken first with the queue still empty, and must wait again. script.then_spurious_wakeup(); script.then([&] { LLD_CHECK(queue.push(3)); }); LLD_CHECK(queue.pop() == 3);}
LLD_TEST(close_wakes_a_waiting_consumer_with_nothing) { Script script; TestQueue queue(2, script); // close() notifies both condition variables, so the waiting pop() // wakes to a closed, empty queue and returns std::nullopt. script.then([&] { queue.close(); }); LLD_CHECK(!queue.pop().has_value());}
LLD_TEST(close_wakes_a_waiting_producer_and_refuses_its_item) { Script script; TestQueue queue(1, script); LLD_CHECK(queue.push(1)); script.then([&] { queue.close(); }); // push(2) waits on the full queue, is woken by close(), and returns // false: its item is dropped. LLD_CHECK(!queue.push(2)); LLD_CHECK(queue.pop() == 1); // what was queued before close can still be taken LLD_CHECK(!queue.pop().has_value());}How this code works: Trace: an item taken by another consumer
The test a_consumer_that_loses_the_item_to_another_waits_again, with
room for 2 items and two steps in the script. “The consumer” is the
pop that the test calls at the end; everything happens in one thread.
| # | What runs | items_ after |
What the consumer’s pop does |
|---|---|---|---|
| 1 | pop(): locks; the queue is open and empty |
empty | counted as waiting (1); ready() is false, so it waits and lets go of the lock |
| 2 | step 1: push(1) |
1 |
not_empty_ is notified; the step has not finished, so it keeps waiting |
| 3 | step 1, continued: pop() by another consumer returns 1 |
empty | still waiting; the other pop found an item, so it did not wait |
| 4 | step 1 ends | empty | it was notified: takes the lock back; ready() is false, so it waits again |
| 5 | step 2: push(2) |
2 |
notified again |
| 6 | step 2 ends | 2 |
takes the lock back; ready() is true; no longer counted (0) |
| 7 | pop() continues |
empty | moves out 2, unlocks, notifies not_full_, returns 2 |
Row 4 is the point of the test: woken, the consumer found the queue
empty and open, and waited again instead of returning. A pop that
waited once, without the loop, would have returned std::nullopt at
row 4, and the check queue.pop() == 2 would fail.
- An item taken by another consumer. While the consumer waits, a producer pushes 1 and notifies; before the consumer wakes, a second consumer, one that was not waiting, takes the 1. The woken consumer finds the queue empty again and must go back to waiting, until a second push. With real threads, the window for this is the time between a notify and the moment the woken thread gets the lock. The push and the other consumer’s pop share one step because the stand-in acts on a notify only when a step ends: that is the only way to put something between the notify and the relock.
- A spurious wakeup. The consumer wakes with nothing in the queue, and must not treat that as an item, or as the queue being closed.
- Close wakes a waiting consumer and a waiting producer (Q3). The producer’s item is refused, and what was queued before the close can still be popped.
These tests finish in a few milliseconds and are the same on every run. They do not need a timeout, a sleep, or luck.
What a scripted test catches
Section titled “What a scripted test catches”To see what these tests are worth, a scratch copy of the queue, not
part of the example, made one plausible change to pop: it waits
once, without a loop. It compiled without warnings with both
compilers:
It looks reasonable: the consumer waits until something happens, and then looks at the queue. But “something happened” is not “there is an item”. The scripted tests, with either compiler, on every run (path shortened):
test_scripted.cpp:76: check failed: queue.pop() == 2test_scripted.cpp:85: check failed: queue.pop() == 38 test(s), 2 failure(s)Line 76 is the item taken by another consumer, and line 85 the
spurious wakeup. In both, pop woke to an empty queue that was not
closed and returned std::nullopt, which tells a consumer the queue
is finished. The failures name the interleaving, and rerunning the
test gives the same failure under a debugger. The other six tests,
which never wake a consumer to an empty queue that is still open,
still passed.
Real threads, waiting for a state
Section titled “Real threads, waiting for a state”Scripted tests use a stand-in, so they cannot show that the queue
works with std::condition_variable and real threads. A few tests
must use both. The rule for those is: wait for a state, never for an
amount of time.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Checks `reached` again and again until it is true, or `limit` has// passed. A test waits for a state this way, never for a fixed time: it// goes on as soon as the state is reached, and if a bug means it never// is, the test fails instead of hanging. The limit is generous because it// only matters when something is wrong.//// Reached is any callable returning bool, usually a lambda. Returns true// once it is reached, false if the limit passes first. [[nodiscard]] makes// the compiler warn if a caller ignores that answer; tests pass it to LLD_CHECK.// The default limit is written in seconds and converts to milliseconds.template <typename Reached>[[nodiscard]] bool eventually(Reached reached, std::chrono::milliseconds limit = std::chrono::seconds(10)) { // steady_clock only moves forward, so changing the computer's clock // cannot end the wait early or make it longer. const auto give_up = std::chrono::steady_clock::now() + limit; while (!reached()) { if (std::chrono::steady_clock::now() >= give_up) return false; // Let other threads run before asking again, instead of hogging the // processor; this is not a sleep for a guessed time. std::this_thread::yield(); } return true;}eventually checks a condition over and over until it is true, giving
up after a limit. The limit is not a guess about how long things take;
it only matters when something is wrong, so it is generous. A test
that uses it goes on as soon as the state is reached, which is usually
at once, and if a bug means the state is never reached, the test fails
with a message instead of hanging until the test runner kills it.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Real threads and the real std::condition_variable. Two threads run here:// the test's own thread, which does every check, and one worker.//// Proves that push() on a full queue blocks, and that one pop() lets it// finish and queue its item.LLD_TEST(a_producer_blocks_while_the_queue_is_full) { BoundedQueue<int> queue(2); LLD_CHECK(queue.push(1)); LLD_CHECK(queue.push(2)); // full now // Written by the producer while the test thread may be reading it, so // it must be atomic: a plain bool here would be a data race. std::atomic<bool> returned{false}; // std::jthread starts a thread running the lambda at once. [&] gives // it `queue` and `returned` by reference; both are declared above, so // they outlive the thread, which is joined before the test ends. // The producer thread: push 3, which blocks while the queue is full, // then record that push came back. std::jthread producer([&] { static_cast<void>(queue.push(3)); returned = true; });
// Counted as waiting means inside push(), so it cannot have returned. LLD_CHECK(eventually([&] { return queue.stats().waiting_producers == 1; })); LLD_CHECK(!returned);
// Taking an item makes room and notifies not_full_, waking the producer. LLD_CHECK(queue.pop() == 1); // room for one // join() waits for the producer thread to finish: push(3) has returned // and `returned` is true by the time it comes back. producer.join(); LLD_CHECK(returned); LLD_CHECK_EQ(queue.stats().size, 2u); // 2 and 3}
// Proves that close() wakes a consumer blocked in pop() on an empty queue,// and that it comes back with std::nullopt.LLD_TEST(close_wakes_a_consumer_blocked_on_an_empty_queue) { BoundedQueue<int> queue(2); std::optional<int> received = 0; // written by the consumer, read after the join // `received` starts as 0, not empty, so an empty value afterwards can only have // come from pop(). A plain optional is safe because the test reads it // only after join(), which makes the thread's writes visible. // The consumer thread: pop, which blocks because the queue is empty. std::jthread consumer([&] { received = queue.pop(); });
LLD_CHECK(eventually([&] { return queue.stats().waiting_consumers == 1; })); // The consumer is known to be blocked, so this tests the wakeup. queue.close(); consumer.join(); LLD_CHECK(!received.has_value());}- A producer blocks while the queue is full. The test fills the
queue, starts a producer, and waits until the queue counts one
waiting producer. That count is not a hint: the producer is counted
only inside
push, and the test can read the count only when the producer has let go of the lock, which, insidepush, it does only while it waits. So when the test sees 1, the producer is blocked, andreturnedmust still be false. Then onepopmakes room, and after the join the producer has returned and its item is queued. - Close wakes a consumer blocked on an empty queue. The same idea: wait until it is counted as waiting, close, join, check.
Compare this with the sleeping tests on the earlier pages. Those were not wrong, and they say what they cannot promise; but here the test knows the thread is blocked, so it tests the wakeup every time, and it does not wait a moment longer than it must. Both tests together take a few hundredths of a second, under ThreadSanitizer too.
Two more details make these tests safe:
- Checks run on the test’s own thread. This site’s harness is not
thread-safe: two threads failing a check at once could corrupt its
count of failures. So the threads only do work and record results,
and the checks happen on the test’s thread.
returnedis astd::atomic<bool>because the test reads it while the producer may still be running.receivedis a plainstd::optional<int>because it is read only afterjoin, and a join makes everything the thread wrote visible to the thread that joined it. - Threads are
std::jthreads. If the test leaves early, because something in it throws, thejthread’s destructor still joins, so the harness reports the exception instead of the program ending instd::terminate, as it would with a joinablestd::thread. A thread that will never finish, as with a bug that leaves it blocked, is the case that is left: then the destructor waits forever, and the test runner’s timeout, 120 seconds in this site’s build, is what ends it.
Stress tests: many threads, many interleavings
Section titled “Stress tests: many threads, many interleavings”Scripted and state-waiting tests check the interleavings someone thought of. A stress test looks for the ones nobody did: many threads, doing many operations, with checks of what must be true however they were interleaved.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// `namespace {` keeps these helpers private to this file.namespace {
constexpr int producers = 4;constexpr int consumers = 3;constexpr int per_producer = 500;constexpr int rounds = 20;
// What one round saw, gathered after every thread has been joined.struct RoundResult { std::vector<std::vector<int>> received; // one list per consumer int stopped_early = 0; // consumers told "closed" before close()};
// One round: 4 producers push 500 numbers each into a queue with room for// 4, while 3 consumers pop until the queue is closed. Every thread is// joined before it returns. Producer p pushes p * 500 to p * 500 + 499, so// every number is different and number / 500 says who pushed it.RoundResult run_round() { BoundedQueue<int> queue(4); // small, so threads block often RoundResult result; // One empty list per consumer, made before any thread starts, so the // outer vector never grows (and never moves the lists) while they run. result.received.resize(consumers); // Both atomic: threads read or change them while others run. std::atomic<bool> closing{false}; std::atomic<int> stopped_early{0}; // A latch counts down from 7. Each thread calls arrive_and_wait(), // which counts one down and blocks until the count reaches 0, so no // thread starts work until all 7 have been created. std::latch start(producers + consumers); // every thread starts at once // This scope owns the consumer threads. A jthread joins in its // destructor, so the closing brace waits for every consumer to finish, // and every local variable above is still alive while they run. { std::vector<std::jthread> threads; for (std::size_t c = 0; c < consumers; ++c) { // emplace_back starts a thread running the lambda. `&` captures // everything else by reference; `&mine = result.received[c]` // names this consumer's own list. Each consumer writes only its // own list, so the lists need no lock. threads.emplace_back([&, &mine = result.received[c]] { start.arrive_and_wait(); // The loop's condition declares `item`: the loop runs while // pop() returns a value, and stops at std::nullopt, which // means closed and empty. *item reads the int. while (const auto item = queue.pop()) { mine.push_back(*item); } // `closing` is set just before close(). If a consumer was // told "closed" while it was still false, the queue lied. if (!closing) ++stopped_early; }); } // An inner scope for the producers: its closing brace joins // them all, so the code after it runs only when every item has been // pushed. { std::vector<std::jthread> senders; for (int p = 0; p < producers; ++p) { // `p` is captured by value: each producer keeps its own // number, while the loop variable moves on. senders.emplace_back([&, p] { start.arrive_and_wait(); for (int i = 0; i < per_producer; ++i) { // push returns false only once the queue is closed, // and it is not closed until every producer is done. static_cast<void>(queue.push(p * per_producer + i)); } }); } } // every producer has finished // Producers done: mark the close as expected, then close. Consumers // drain what is left and then get std::nullopt. closing = true; queue.close(); } // every consumer has stopped // Reads the atomic count into the plain int. result.stopped_early = stopped_early; return result;}
} // namespace
// Runs 20 rounds and checks, for each one, what must hold whatever the// interleaving: every number arrives exactly once, each consumer saw each// producer's numbers in increasing order, and no consumer stopped early.// All checks run here, on the test's thread, after the round's threads are// joined.LLD_TEST(many_threads_lose_nothing_duplicate_nothing_and_keep_order) { for (int round = 0; round < rounds; ++round) { const RoundResult result = run_round(); std::vector<int> all; bool in_order = true; for (const std::vector<int>& mine : result.received) { // Append this consumer's list to `all`. all.insert(all.end(), mine.begin(), mine.end()); std::vector<int> last(producers, -1); // per producer, the last item seen for (const int item : mine) { // item / per_producer is the producer's index, 0 to 3. // Within one consumer, each producer's numbers must rise. // `in_order && ...` keeps it false once it is false. in_order = in_order && item > last[static_cast<std::size_t>(item / per_producer)]; last[static_cast<std::size_t>(item / per_producer)] = item; } } // Sorted, exactly 2'000 numbers that are 0, 1, 2, ... in turn // means none was lost and none came twice. std::sort(all.begin(), all.end()); bool each_once = all.size() == std::size_t{producers * per_producer}; for (std::size_t i = 0; each_once && i < all.size(); ++i) { each_once = all[i] == static_cast<int>(i); } LLD_CHECK(each_once); LLD_CHECK(in_order); LLD_CHECK_EQ(result.stopped_early, 0); }}How this code works: One round of the stress test, thread by thread
run_round uses eight threads: the test’s own thread, three consumers,
and four producers.
- The test’s thread sets up. A queue with room for 4, one empty list per consumer, the two atomics, and a latch that counts down from 7. All of them are declared before any thread starts, so they outlive every thread.
- It starts the three consumers, then the four producers. Each
new thread first calls
start.arrive_and_wait(), counting the latch down by one and blocking until it reaches 0. The seventh thread to arrive releases all seven together. - Each producer, numbered 0 to 3, pushes 500 numbers, from
p * 500top * 500 + 499: producer 2 pushes 1000 to 1499. With room for only 4 items, producers block inpushoften. - Each consumer pops until
popreturnsstd::nullopt, appending each number to its own list. No two threads write the same list. - The test’s thread waits for the producers. The inner block ends,
and each producer’s
jthreaddestructor joins it. Now every one of the 2000 numbers has been pushed. - It closes the queue. First
closing = true, thenclose(). The consumers drain whatever is left and then seestd::nullopt. One that sawstd::nulloptwhileclosingwas still false would count itself instopped_early. - It waits for the consumers. The outer block ends and their
jthreads join. Only now are the lists read, in the test’s thread.
The checks then use only facts that hold for every interleaving. Say
one consumer’s list begins 500, 0, 501, 1, 1500. That is in order:
for producer 1 it is 500, 501, for producer 0 it is 0, 1, and
1500 is the first from producer 3. A list with 501 before 500
would not be. And sorting every list together must give exactly
0, 1, 2, ..., 1999: a lost number leaves a gap, and a repeated one
shifts everything after it.
Its choices, each for a reason:
- The queue is small, room for four items, so producers and consumers block often; most bugs in a blocking queue are in the blocking.
- A
std::latchstarts every thread at once. Without it, the first threads started might finish before the last ones begin, and the test would mostly test one thread at a time. - It checks what of Q4 can be observed: every item arrives
exactly once, and each consumer saw each producer’s items in
increasing order. With three consumers, the order across consumers
cannot be seen, so that part of Q4 is not checked. It
also checks that no consumer was told “closed” before
closewas called. - It repeats, 20 rounds, because each round produces different interleavings.
- It is fast enough for every build, about a third of a second on this machine, half a second under ThreadSanitizer. A stress test that takes minutes belongs in a separate, longer run, like the slow property tests on the property-based testing page.
Against the scratch queue with the waiting bug, it did find something, but not in a helpful form. Built with GCC and run 30 times, each with a 10-second limit, the stress test hung in all 30 runs; the correct queue passed all 30. In a later set of 10 runs, 6 first printed failures of the check that no consumer stops early, from one to eight of them, for rounds that finished, and then hung; the other 4 hung with nothing printed. Each failure looked like this:
actual: 2 expected: 0test_stress.cpp:134: check failed: result.stopped_early == 0(This site’s harness prints the two values first, then the line that failed.) The test runner reports a timeout, with any such lines in its output. A scratch copy of the stress test with a watchdog thread, which printed the queue’s state after five seconds, showed what happened at the hang. In each of 6 runs, the round that hung had all three consumers stopped early, a full queue, and three producers waiting; in 5 of them, earlier rounds had already finished with two consumers stopped early. The end of one run:
...round 1: a consumer stopped earlyround 1: a consumer stopped earlyround 1: a consumer stopped earlyafter 5 s, round 1: size 4, waiting producers 3, waiting consumers 0Each consumer had woken to an empty queue, taken std::nullopt to
mean “closed”, and stopped. While at least one consumer was left, the
round finished and the check failed; once all three had stopped, the
producers waited forever for room, and the round never reached
close, or its checks. Built with Clang and ThreadSanitizer, which
runs the threads more slowly, the pattern was the same: four rounds
finished with two consumers stopped early, and then a round hung.
That is typical of stress tests. They find real bugs, and they are worth having, but the same bug can show up as a hang, a wrong count, or nothing at all, depending on the machine and the build. When a stress test fails, the next step is to work out the interleaving and write a scripted test for it, which then fails the same way every time.
ThreadSanitizer: what it finds and what it misses
Section titled “ThreadSanitizer: what it finds and what it misses”ThreadSanitizer (TSan) watches a running program’s memory accesses and synchronization, and reports a data race: two threads touching the same memory, at least one writing and at least one not atomic, with nothing ordering the two. It was silent on the waiting bug above, and that is correct: every access there was under the mutex. The bug was a wrong decision, a race condition in the logic, not a data race, and TSan does not know what the queue is supposed to do.
For a bug it does find, a second scratch copy of the queue left the
lock out of stats(), with the comment “Only reads three numbers, so
no lock.” That is a data race, since the waiting counts are written by
other threads under the lock while stats() reads them without it,
and so it is undefined behaviour. Built with GCC without sanitizers,
the thread tests passed in 100 runs out of 100: on this machine
the reads happen to give sensible numbers. Built with Clang and TSan,
the same tests reported two data races, the first like this (paths
shortened, and most stack frames cut):
WARNING: ThreadSanitizer: data race Read of size 8 at 0x7ffe1d8ed128 by main thread: #0 shipping::BoundedQueue<int, std::condition_variable>::stats() const bounded_queue.hpp:194:28 #1 a_producer_blocks_while_the_queue_is_full()::$_2::operator()() const test_threads.cpp:42:5 ... Previous write of size 8 at 0x7ffe1d8ed128 by thread T1 (mutexes: write M0): #0 shipping::BoundedQueue<int, std::condition_variable>::Waiting::Waiting(unsigned long&) bounded_queue.hpp:86:73 #1 shipping::BoundedQueue<int, std::condition_variable>::push(int) bounded_queue.hpp:122:27 #2 a_producer_blocks_while_the_queue_is_full()::$_0::operator()() const test_threads.cpp:37:33 ...SUMMARY: ThreadSanitizer: data race bounded_queue.hpp:194:28 in shipping::BoundedQueue<int, std::condition_variable>::stats() constThe report names both sides: the read in stats(), from the test’s
eventually check, and the write in Waiting’s constructor, inside
push, on the producer’s thread, which held mutex M0. The program’s
own checks all passed, 2 test(s), 0 failure(s), but TSan made the
process exit with status 66, so the test runner counts it as a
failure.
“It gave sensible numbers” is not a defence. Because a data race is
undefined behaviour, the compiler may assume no other thread changes
the counts while stats() runs, and a different compiler, optimization
level, or platform is free to make the result wrong. The fix is the one line
the example has: take the lock.
The experiments side by side. The third row is a later one, suggested
in review: close calling notify_one instead of notify_all, so
only one of the threads waiting is told the queue closed:
| Bug | Scripted tests | Thread tests | Stress test | TSan |
|---|---|---|---|---|
pop waits once, without a loop |
Fail on every run, at the line | Pass, 30 of 30 runs | Often a wrong count of stops in early rounds, then always a hang | Nothing reported: no data race |
stats() reads without the lock |
Pass | Pass, 100 of 100 runs | Pass: it never calls stats() |
Two data races, in the thread tests |
close notifies one waiter, not all |
Pass | Pass | Hang, 5 of 5 runs | Nothing reported: no data race |
No single column catches all three. That is the practical case for using more than one kind of test on concurrent code.
Why passing tests do not prove correctness
Section titled “Why passing tests do not prove correctness”Every test on this page passed with the correct queue, many times, and under TSan. That is good evidence. It is not proof, for reasons that apply to any test of concurrent code:
- Only some interleavings ran. The number of possible orders grows very fast with the number of threads and steps. A stress test samples a tiny fraction of them, and the same few, the ones this machine’s scheduler tends to produce, over and over.
- The machine hides some bugs. x86 processors, like the one these tests ran on, keep most memory operations in program order. Code that uses atomics with too weak an ordering can pass every test on x86 and fail on an ARM processor, which reorders more. The queue here uses only a mutex and condition variables, which give the same guarantees everywhere, which is one reason to prefer them.
- Tests check what someone wrote down. A requirement nobody turned into a check, such as fairness between producers, is not tested by any number of runs.
So the main evidence for concurrent code is still the argument for
why it is right, and tests check the argument. For this queue the
argument is short. Every read and write of the state is under one
mutex, so each operation sees the state as a whole. Each wait is in a
loop that rechecks its condition, so a thread goes on only when the
condition holds. Every change that could let a waiting thread go on
notifies: push notifies consumers, pop notifies producers, and
close notifies everyone. A design that keeps the argument this short
is easier to test, and easier to trust when the tests pass.
Running them
Section titled “Running them”The example labels its tests by kind. From the examples directory,
after the presets have been configured and built:
ctest --preset gcc-debug -L unit # the scripted tests, among othersctest --preset gcc-debug -L concurrency # tests with real threads, including the stress testctest --preset gcc-debug -L stress # only the stress testctest --preset tsan # every test labelled concurrency, under ThreadSanitizerThe last needs its own build first, cmake --preset tsan and then
cmake --build --preset tsan.
The tsan test preset runs the tests labelled concurrency; the
tests with real threads from the advanced concurrency pages have the
same label. On this machine, the six of them take about a second and
a half under TSan in all, so there is no reason to skip them.
When this approach fits, and when it does not
Section titled “When this approach fits, and when it does not”Scripted tests fit when shared state is guarded by one mutex and the interesting moments are the waits: queues, pools, latches, rate limiters. They are the cheapest way to pin down how a class behaves in the interleavings that matter, and they are as fast and repeatable as any unit test.
They fit less well when:
- The code is lock-free, with atomics. Interleavings happen at every load and store; the tools in the callout above are a better match, together with a careful argument.
- The class waits on something other than a condition variable, such as a socket or a timer. The seam then belongs at that wait: a clock or a connection the test controls, as on the test doubles page.
- The waits are private details that change often. A script describes exactly where a thread waits, so it is tied to the design. For a class whose waiting is still being reworked, a few state-waiting tests and a stress test may be the better first step.
Tests with real threads are always needed, at least a few, because only they test the real condition variable. Stress tests are worth having for any shared class, as long as their failures are followed up with a scripted test.
Common mistakes
Section titled “Common mistakes”- Sleeping to make an interleaving “certain”. A sleep makes it likely. Wait for a state the code reports, or script the interleaving.
- Checking from another thread. Unless the test harness says it is thread-safe, record results in the threads and check them on the test’s thread, after a join or through an atomic.
- No limit on a wait. A test that waits for a state with no limit
turns a bug into a hang.
eventuallygives up; the build’s timeout is the last line of defence. - A stress test with weak checks. Many threads and no check of “each item exactly once” is a test that passes as long as nothing crashes.
- Treating a stress failure as noise. A failure that happened once is a real interleaving that will happen again in production. Find it, and script it.
- Trusting a clean TSan run as proof. It found no data race in what ran. It says nothing about logic, or about code that did not run.
- Leaving out the lock “because it is only a read”. That is a data race, so undefined behaviour, even when every test passes.
When the requirements change
Section titled “When the requirements change”- “When the queue is full, drop the oldest line instead of
waiting.” That is the drop-oldest policy from the backpressure
page.
pushnever waits, so the scripted tests of a waiting producer go, and new ones check which item was dropped. The stress test’s “exactly once” check becomes “every item is delivered once or counted as dropped”, which needs the queue to count what it drops. The checks follow the requirements, not the code. - “A consumer should give up after a second with nothing to take.”
popgains a time limit and useswait_for. The stand-in condition variable then needs await_fortoo, and a script step that means “the time ran out”, so that the test, not the clock, decides when the time is up. That is the clock seam from the test doubles page, arriving at the condition variable. - “Several shippers, one per destination.” More consumers changes nothing in the scripted tests, but the stress test should use the new numbers, and Q4’s “in order” becomes “in order per consumer”, which is what the test already checks.
Exercise
Section titled “Exercise”Exercise: Make a concurrent test deterministic
A service sends a heartbeat, “beat 1”, “beat 2”, and so on, once per period, from its own thread. This is the code and its test, as compiled for this exercise; the test passes:
// Sends "beat 1", "beat 2", ... once per period, on its own thread, until// it is destroyed.class Heartbeat {public: // send: what to do with each beat, such as writing it to the network. // The jthread starts last and runs run() on its own thread. A jthread // passes its stop token as the first argument to a function that takes // one; its destructor requests a stop and then joins. Heartbeat(std::function<void(std::string)> send, std::chrono::milliseconds period) : send_(std::move(send)), period_(period), thread_([this](std::stop_token stop) { run(stop); }) {}
private: // Runs on the heartbeat's thread. `for (int n = 1;; ++n)` has no // condition, so it loops until the return below. void run(std::stop_token stop) { for (int n = 1;; ++n) { // Wait one period, then check whether the owner asked to stop. std::this_thread::sleep_for(period_); if (stop.stop_requested()) return; send_("beat " + std::to_string(n)); } }
std::function<void(std::string)> send_; std::chrono::milliseconds period_; std::jthread thread_; // last: stopped and joined before the members it uses go};
// Starts a heartbeat with a 100 ms period, lets 350 ms pass, destroys it,// and expects exactly three beats. 100ms and 350ms are std::chrono// literals: durations written with their unit.LLD_TEST(three_beats_in_350_milliseconds) { std::vector<std::string> sent; // read only after the heartbeat's thread is joined { // The lambda is the send function: it stores each beat in `sent`. Heartbeat heartbeat([&](std::string beat) { sent.push_back(std::move(beat)); }, 100ms); std::this_thread::sleep_for(350ms); } // the heartbeat is destroyed here: its thread is stopped and joined const std::vector<std::string> expected{"beat 1", "beat 2", "beat 3"}; LLD_CHECK(sent == expected);}- The test passed every time it was run on this machine. What is wrong with it anyway? Give at least two problems.
- The test hides a problem in
Heartbeatitself. What is it? (Think about a period of an hour.) - Change the design so that the loop’s behaviour can be tested in one thread, with no time passing, and so that the problem from part 2 is fixed. Then write the tests.
Show the explained answer
-
Problems with the test:
- It depends on timing. It expects beats at 100, 200, and 300 ms, and the end of the test at 350 ms, so a pause of about 50 ms in the wrong place, on a busy build machine, under a sanitizer, or in a debugger, changes the number of beats. It passed every time on this machine, even sharing one core with eight busy loops, but that says how this machine behaves, not that the test is sound.
- It is slow. It took about 400 ms on this machine: 350 ms of sleep, then, as part 2 explains, up to one more period in the destructor. A test suite of such tests takes minutes.
- It tests the clock as much as the code. The interesting behaviour, a numbered beat after each period, has nothing to do with real time.
-
Destroying a
Heartbeatcan take a whole period.sleep_fordoes not notice a stop request, so thejthread’s destructor asks the thread to stop and then waits for it to finish its sleep. With a 100 ms period, the test does not notice. With a period of an hour, shutting the service down takes up to an hour. -
Separate the loop from the waiting, and make the wait a seam. The real wait uses
std::condition_variable_any, whosewait_forcan take a stop token and returns early when a stop is requested. This was compiled with both compilers and run, and also run under ThreadSanitizer, which reported nothing:// The loop, with the waiting as a seam: wait(stop) returns true after one// period, or false once a stop has been requested.// Wait is any callable that takes a stop token and returns bool: the real// PeriodWait below, or a lambda in a test. The loop sends beat n after// each period and ends as soon as wait returns false.template <typename Wait>void run_heartbeat(std::stop_token stop, Wait& wait,const std::function<void(std::string)>& send) {for (int n = 1; wait(stop); ++n) {send("beat " + std::to_string(n));}}// The real wait: one period, cut short by a stop request.class PeriodWait {public:explicit PeriodWait(std::chrono::milliseconds period) : period_(period) {}// operator() makes a PeriodWait callable like a function: wait(stop).bool operator()(std::stop_token stop) {// condition_variable_any waits need a locked lock, even though// there is no shared data here.std::unique_lock lock(mutex_);// Nothing notifies this condition variable; it is here so that a// stop request can end the wait early.// This wait_for returns when the period has passed or a stop is// requested, whichever comes first. Its predicate is never true,// so nothing else ends it; its result is ignored on purpose.static_cast<void>(stopped_.wait_for(lock, stop, period_, [] { return false; }));// true: a full period passed; false: the owner asked to stop.return !stop.stop_requested();}private:std::mutex mutex_;std::condition_variable_any stopped_;std::chrono::milliseconds period_;};class Heartbeat {public:Heartbeat(std::function<void(std::string)> send, std::chrono::milliseconds period): send_(std::move(send)),wait_(period),thread_([this](std::stop_token stop) { run_heartbeat(stop, wait_, send_); }) {}private:std::function<void(std::string)> send_;PeriodWait wait_;std::jthread thread_; // last: stopped and joined before the members it uses go};// The loop's behaviour, in one thread: no time passes.LLD_TEST(a_beat_follows_each_period_numbered_from_one) {std::vector<std::string> sent;int periods = 0;// A fake wait: returns at once, true for the first three calls// (periods 1, 2, 3) and false on the fourth, which ends the loop.auto three_periods = [&periods](std::stop_token) { return ++periods <= 3; };// A default-constructed stop_token can never be asked to stop; the// fake wait ignores it anyway. No thread is started: the loop runs// here, on the test's thread.run_heartbeat(std::stop_token{}, three_periods,[&sent](std::string beat) { sent.push_back(std::move(beat)); });const std::vector<std::string> expected{"beat 1", "beat 2", "beat 3"};LLD_CHECK(sent == expected);}// The real wait ends early on a stop: with an hour's period, destroying the// heartbeat at once must not take an hour, and nothing is sent.LLD_TEST(destroying_a_heartbeat_stops_it_without_waiting_for_the_period) {std::vector<std::string> sent; // read only after the heartbeat's thread is joinedconst auto started = std::chrono::steady_clock::now();{Heartbeat heartbeat([&sent](std::string beat) { sent.push_back(std::move(beat)); }, 1h);} // destroyed at once: the stop request must cut the hour's wait shortLLD_CHECK(std::chrono::steady_clock::now() - started < 10s);LLD_CHECK(sent.empty());}// A lower bound on real time is safe to test: wait_for with a predicate// that is never true cannot return before the period has passed.LLD_TEST(a_real_period_lasts_at_least_the_period) {PeriodWait wait(20ms);// Called directly on this thread, with a token that is never stopped,// so it must wait the full period and then return true.const auto started = std::chrono::steady_clock::now();LLD_CHECK(wait(std::stop_token{}));LLD_CHECK(std::chrono::steady_clock::now() - started >= 20ms);}The three tests together took about 20 milliseconds. The first is a plain unit test of the loop: the fake wait says “a period passed” three times, then “stopped”. The second uses the real wait and a real thread, but waits for nothing: it checks only that a stop ends the wait at once, which was the bug. Its 10-second bound is not a timing guess; it is there so that, if the bug comes back, the test fails rather than taking an hour, or, if the wait never ends, the build’s timeout fails it. The third checks the real wait from the other side:
PeriodWaitis this code, and a predicate that is always true would make the heartbeat send beats in a busy loop while the first two tests still passed. A scratch copy with that mistake failed it. Its bound is safe because it is a lower one: the wait cannot end early, but it can end late on a busy machine, so a test that the period is not too long would be flaky.The
jthreadis the last member, so it is destroyed first: its destructor requests a stop and joins beforewait_andsend_, which the thread uses, are destroyed.
Summary
Section titled “Summary”- Tests of concurrent code are hard to trust because the order of threads changes from run to run. Sleeping to make an order likely is slow and still not certain.
- Design for testing: a seam where threads wait, so a test can script what happens meanwhile, and a report of who is waiting, so a test with real threads can wait for a state.
- Scripted tests play out one interleaving each, in one thread, the same way every run. They catch the bugs someone thought to script, and name them precisely.
- Tests with real threads wait for states, with a limit, keep their
checks on the test’s thread, and use
std::jthreadso a failure still joins. - Stress tests find interleavings nobody thought of, but report them as hangs or odd counts. Follow up every stress failure with a scripted test.
- ThreadSanitizer finds data races in what ran, and nothing else. A logic race passed it; an unlocked read that passed every ordinary run failed it.
- Passing tests are evidence, not proof. Keep the design simple enough that the argument for its correctness is short.