Thread safety and synchronization
What you will learn on this page
Section titled “What you will learn on this page”- What a data race is, why C++ makes it undefined behavior, and why “it only loses a few counts” is the wrong way to think about it.
- The difference between a data race and a broken invariant: code can be free of data races and still show readers values that never existed together.
- How to classify shared state: which values are independent
(one
std::atomiceach), which must agree (one mutex for all of them), and which should not be shared at all. - How to use
std::scoped_lockandstd::condition_variable, and why a thread-safe class returns copies, not references. - How to write a thread-safety contract for a type, so that its users know what they may do from several threads.
The concurrency pages answer three questions a design must answer when threads share work. This page and the page on deadlocks cover correctness: shared state stays consistent. Asynchronous work, cancellation, and shutdown covers coordination, and Backpressure and bounded queues covers scarcity.
The problem
Section titled “The problem”A web service handles requests on a pool of 8 threads. It keeps statistics about them:
- T1. Every request handler records its request: the endpoint, how long it took, and whether it failed. All 8 threads do this at once.
- T2. A dashboard thread reads the totals and the per-endpoint figures every second. What it shows must be consistent: the totals must equal the sum of the endpoints, and it must never show more failures than requests.
- T3. A page-view counter goes up on every request. It is read alone, now and then.
- T4. Tests, and the code that drains the service before shutdown, must be able to wait until a given number of requests has been recorded, without polling.
- T5. Recording must be cheap. Nothing slow, such as writing to a log or a socket, may happen while other threads are kept waiting.
The first version: a plain counter
Section titled “The first version: a plain counter”The page-view counter started like this:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
class RacyCounter { // FLAWED: a page-view counter that many threads sharepublic: void record() { ++hits_; } // read, add one, write: three steps // record() is where it goes wrong. main() has four threads call it on // the same object at once, and nothing (no mutex, no std::atomic) // orders their accesses to hits_. Two threads can both read the same // old value, both add one, and both write the same new value: one // count is lost. That is a data race, which C++ calls undefined // behavior: the compiler may assume no other thread touches hits_, so // it may keep it in a register or merge increments, and the final // number can be anything. // Reading hits_ while a thread is still in record() would race too. // main() reads it only after every thread is joined, so that read races // with nothing, but the earlier races mean no particular total is promised. std::int64_t hits() const { return hits_; }
private: std::int64_t hits_ = 0; // shared by every thread, guarded by nothing};This code is compiled by the build but never run as a test.
++hits_ looks like one step. It is three: read hits_, add one,
write the result back. Two threads can interleave those steps:
Text description of the diagram
Thread A reads 41 from hits_. Before it writes, thread B also reads
41. Each adds one and gets 42. A writes 42, then B writes 42. Two
increments happened, but hits_ grew by only one. This picture is a
way to see the problem; the C++ rules below say that once two threads
touch the counter like this, the program has no defined behavior at
all.
Diagram source (Mermaid)
sequenceDiagram
participant A as Thread A
participant H as hits_
participant B as Thread B
A->>H: read 41
B->>H: read 41
A->>A: add one, 42
B->>B: add one, 42
A->>H: write 42
B->>H: write 42
Note over A,B: Two increments, but hits_ grew by oneWhen we ran the flawed program on a 16-thread machine, four threads
each called record() one million times. Three runs printed
1,151,269, then 1,649,323, then 1,746,502, out of 4,000,000. Every run
was different, and none was right. Those runs used the unoptimized
gcc-debug build. An optimized (-O2) build of the same code printed
exactly 4,000,000 in our runs, because the compiler combined each
thread’s increments. A correct-looking answer does not make the
program correct.
The loss is not the real problem. The C++ standard calls this a
data race: two threads
access the same memory location, at least one access is a write, at
least one is not atomic, and nothing orders one before the other. A
program with a data race has undefined behavior. The compiler is
allowed to assume that no other thread changes hits_ while this
thread uses it, so it may keep the value in a register, combine
increments, or move them; the result can be any number, a value that
was never written, or something stranger. “It loses a few counts” is
what one compiler did on one machine, not a promise.
Finding it with ThreadSanitizer
Section titled “Finding it with ThreadSanitizer”ThreadSanitizer (TSan) is a compiler option, -fsanitize=thread,
that watches every memory access while the program runs and reports
data races. The examples are built with it as one of their presets.
Run under TSan, the flawed program printed this report, shortened
here:
WARNING: ThreadSanitizer: data race Write of size 8 at 0x7ffecc069e00 by thread T2: #0 RacyCounter::record() racy_counter.cpp:14:21 Previous write of size 8 at 0x7ffecc069e00 by thread T1: #0 RacyCounter::record() racy_counter.cpp:14:21SUMMARY: ThreadSanitizer: data race racy_counter.cpp:14:21 in RacyCounter::record()Line 14 is ++hits_. TSan then made the program exit with status 66
instead of 0, so a test run under TSan fails when a race happens.
Making each number atomic is not enough
Section titled “Making each number atomic is not enough”The obvious fix is to make every counter a std::atomic. The request
totals were changed that way:
Flawed (intentional)Demonstrates a mistake on purpose. Do not copy it; see the corrected version.
// FLAWED, in a different way: the first "fix", one std::atomic per number.// Every single access is now safe, so there is no data race and no lost// count. But the rule that matters, "never more failures than requests",// is about two numbers together, and nothing lets a reader see both at// the same moment. The two atomics are two separate pieces of data.class TornStats {public: // Counts one request, and a failure if it failed. Each fetch_add(1) // reads, adds one, and writes as one indivisible step. The request is // counted first, so at any single moment failures <= requests. void record(bool failed) { requests_.fetch_add(1); if (failed) { failures_.fetch_add(1); // a second, separate step } } // Each load is safe on its own; the pair is not read at one moment. // Where it goes wrong: a caller that calls requests() and then // failures() makes two reads at two moments. If writers record more // failed requests in between, the caller gets the old request total // and a newer, larger failure total: more failures than requests, a // pair of values that never existed together. std::int64_t requests() const { return requests_.load(); } std::int64_t failures() const { return failures_.load(); }
private: // {0} starts each counter at zero. Two atomics, and no lock that // covers both of them. std::atomic<std::int64_t> requests_{0}; std::atomic<std::int64_t> failures_{0};};fetch_add on a std::atomic is one indivisible step, so no update
is lost, and there is no data race: TSan reported nothing for this
class. But T2 is still broken. record() changes two values, and a
reader that loads them one after the other sees each at a different
moment. In the flawed program, every request fails, so at any single
moment the two numbers are equal or one apart. A reader loaded
requests, then failures, one million times while a writer
recorded. In one run, 50,605 of those pairs of reads saw more failures than
requests, a pair of values that never existed together. (“At any
single moment” makes sense here because these atomics use the default
std::memory_order_seq_cst, under which all threads agree on one order
of the operations.) Swapping the two loads would hide this one symptom,
but no load order can make the totals agree with every endpoint.
That is a race condition without a data race: every access is safe, and the result is still wrong, because the rule that matters spans two values. TSan finds data races; it does not know your invariants, so it cannot find this.
Step 1: classify the shared state
Section titled “Step 1: classify the shared state”Before choosing any tool, list what is shared, who writes it, who reads it, and what it must agree with:
| Data | Written by | Read by | Must agree with | Protection |
|---|---|---|---|---|
| page views | every handler | anyone, now and then | nothing | one std::atomic |
| total requests, total failures | every handler | the dashboard, tests | each other, and every endpoint’s figures | one mutex for all of them |
| each endpoint’s requests, failures, latency | every handler | the dashboard, tests | the totals | the same mutex |
| a snapshot the dashboard is drawing | nobody, after it is made | one thread | itself only | none: it is not shared |
- A value that must agree with nothing can be one
std::atomic. - Values that must agree with each other need one lock that covers every read and every write of all of them. One mutex per value would be the atomic mistake again, with more steps.
- Data that is not shared needs no protection. The best way to make something thread safe is to stop sharing it: give each thread its own copy, or give the data to one thread and send it messages.
The rule behind the table: one mutex guards one invariant. The invariant decides which data goes under which lock.
One independent number: std::atomic
Section titled “One independent number: std::atomic”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Thread safety: safe. Any number of threads may call any member at the// same time. No record() is ever lost; once the recording threads have// been joined, hits() is exact.//// The idea: the page-view count must agree with nothing else, so one// std::atomic is all the protection it needs. No mutex, no lock.class HitCounter {public: // fetch_add(1) reads the value, adds one, and writes it back as one // indivisible step: no other thread can slip in between, so no // increment is lost. noexcept: it cannot throw. void record() noexcept { hits_.fetch_add(1); } // load() reads the current value; it is always a value the counter // really held. While other threads still record, it is already out of // date when it returns. [[nodiscard]] makes the compiler warn if a // caller ignores the result. [[nodiscard]] std::int64_t hits() const noexcept { return hits_.load(); }
private: // Starts at zero. Both calls above use the default memory order, // std::memory_order_seq_cst, the strongest and simplest one. std::atomic<std::int64_t> hits_{0};};fetch_add(1)reads, adds, and writes as one indivisible step. No other thread can come between the read and the write, so nothing is lost.load()reads the current value. It is always a value that the counter really held.- This is enough only because nothing else depends on the number. The moment a second value has to agree with it, an atomic stops being the right tool.
Values that must agree: one mutex
Section titled “Values that must agree: one mutex”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The figures for one endpoint, such as "/orders". A plain value: it has// no lock of its own. Inside RequestStats it is guarded by that class's// mutex; inside a Snapshot it is a private copy.struct EndpointSummary { std::int64_t requests = 0; std::int64_t failures = 0; std::chrono::microseconds total_latency{0}; // sum over all requests
// "= default" asks the compiler to write ==, comparing the three // members in order. The tests use it to compare a whole summary at once. friend bool operator==(const EndpointSummary&, const EndpointSummary&) = default;};
// A copy of the statistics at one moment. It shares nothing with the// RequestStats it came from, so it needs no lock.struct Snapshot { std::int64_t requests = 0; // across all endpoints std::int64_t failures = 0; // across all endpoints // Endpoint name -> its figures, sorted by name. std::less<> (with empty // angle brackets) lets find() take a std::string_view directly, // without first building a std::string to compare against. std::map<std::string, EndpointSummary, std::less<>> endpoints;};VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Thread safety: safe. Any number of threads may call any member at the// same time. Every member locks mutex_ for the whole time it reads or// writes the guarded data, so no thread ever sees half of a record().//// Invariant (holds whenever mutex_ is not held): requests_ is the sum of// every endpoint's requests, and failures_ the sum of their failures.class RequestStats {public: // Records one request to `endpoint`. The first request to a new // endpoint adds an entry to the map, which allocates and can throw; // if it throws, nothing at all was recorded. Wakes any waiting thread. void record(std::string_view endpoint, std::chrono::microseconds latency, bool failed);
// A consistent copy: the totals and every endpoint at the same moment. // Returned by value, so the caller can read it with no lock. [[nodiscard]] Snapshot snapshot() const;
// Blocks the calling thread until at least `count` requests have // been recorded. There is no time limit and no way to cancel: if the // count is never reached, the caller waits forever. void wait_for_requests(std::int64_t count) const;
private: mutable std::mutex mutex_; // mutable: const members lock it too // Lets a thread sleep until record() says "something changed". // record() notifies it; wait_for_requests() waits on it, always // together with mutex_. Also mutable, because a const member waits on it. mutable std::condition_variable recorded_;
// Guarded by mutex_. std::int64_t requests_ = 0; std::int64_t failures_ = 0; std::map<std::string, EndpointSummary, std::less<>> endpoints_;};The header says three things a user of the class needs to know: it is safe to use from any number of threads, which mutex guards which data, and the invariant that mutex protects.
mutable std::mutex mutex_.snapshot()isconst: it does not change the statistics. It still has to lock the mutex, and locking changes the mutex.mutablesays that the mutex is not part of the object’s value, which is exactly what Const correctness saidmutableis for. The condition variable ismutablefor the same reason.- “Guarded by
mutex_” is a comment, but it is the most important line in the class. Every member function that touches the guarded data must hold that mutex while it does.
Recording
Section titled “Recording”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Adds one request to the endpoint's figures and to the totals, as one// step that no other thread can see half of. Called by every handler// thread at once. The idea: lock mutex_, find or create the endpoint,// change every number, unlock, and only then wake the waiting threads.void RequestStats::record(std::string_view endpoint, std::chrono::microseconds latency, bool failed) { { // this inner block is the lock's scope: mutex_ is held only inside it // Locks mutex_ now (waiting if another thread holds it) and unlocks // it when `lock` is destroyed at the closing brace, on every path // out, including an exception. const std::scoped_lock lock(mutex_); // find() takes the string_view directly, thanks to std::less<>. // It returns an iterator to the entry, or end() if there is none. auto found = endpoints_.find(endpoint); if (found == endpoints_.end()) { // The only step that can throw, and it comes before any change. // std::string(endpoint) copies the characters: the map must own // its key, while the view may point into the caller's string. // emplace returns a pair (iterator, inserted?); .first is the // iterator to the new entry. found = endpoints_.emplace(std::string(endpoint), EndpointSummary{}).first; } // A reference to the summary inside the map, so the changes below // update the map itself, not a copy. found->second is the value // part of the (name, summary) entry. EndpointSummary& summary = found->second; // From here on nothing can throw: plain additions only. The totals // and the endpoint change together, so the invariant holds again // by the time the lock is released. ++summary.requests; summary.total_latency += latency; ++requests_; if (failed) { ++summary.failures; ++failures_; } } // unlocked here, before waking anyone recorded_.notify_all();}std::scoped_locklocks the mutex in its constructor and unlocks it in its destructor, so the mutex is unlocked on every path out of the block, including an exception. Callinglock()andunlock()by hand is the manual resource management that RAII replaces.- The whole update is under the lock. Another thread can lock the
mutex only before the update starts or after it ends, so no thread
ever sees half of a
record(). That is T2. - The step that can throw comes first. Adding a new endpoint
allocates and can throw; it happens before any number changes. So if
record()throws, nothing was recorded, which is the strong guarantee from Exception safety. An exception would also unlock the mutex on the way out. - The block ends before
notify_all(). Waking the waiting threads after unlocking means they do not wake up only to wait for the mutex this thread still holds. Notifying while holding the lock would also be correct, and can be slightly slower. One exception: if a waiter may destroy the object as soon as it sees the condition, notify while still holding the lock. HereRequestStatsoutlives every waiter. - The lock is held only for a few additions and one map lookup and, the first time an endpoint is seen, one insertion that allocates. Nothing slow happens inside it (T5). If recording also had to write a log line, that line would be built and written after the block ends.
Reading: return a copy
Section titled “Reading: return a copy”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Copies all the guarded data into a new Snapshot while holding the lock,// so the copy shows one moment: no record() can run halfway through it.// Copying the map allocates and can throw; then the lock is released on// the way out and nothing has changed.Snapshot RequestStats::snapshot() const { const std::scoped_lock lock(mutex_); // The returned Snapshot is built before `lock` is destroyed, so all // three copies are made while mutex_ is still held. The caller gets // its own map, which no other thread can touch. return Snapshot{requests_, failures_, endpoints_}; // copies while locked}snapshot() copies everything while holding the lock and returns the
copy. The dashboard can then take as long as it likes to draw it,
without holding up any handler, and it never sees a half-made update.
Returning a reference to the map instead would be a bug that no
lock can fix. The lock would be released when snapshot() returns,
and the caller would read the map later, while handlers change it: a
data race again. A thread-safe class must never let a pointer or
reference to its guarded data escape from inside the lock.
Waiting for something to happen: std::condition_variable
Section titled “Waiting for something to happen: std::condition_variable”T4 asks for a thread that waits until enough requests have been recorded. Checking in a loop, with a sleep, wastes time and wakes up late. A condition variable lets a thread sleep until another thread says that something changed:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Sleeps until at least `count` requests have been recorded. It returns// at once if they already have. It has no time limit.void RequestStats::wait_for_requests(std::int64_t count) const { // unique_lock, not scoped_lock: wait() must be able to unlock the mutex // and lock it again, and only a unique_lock lets it do that. std::unique_lock lock(mutex_); // wait() unlocks while it sleeps and locks again before it returns. It // can wake for no reason, so it checks the condition each time. // The lambda is the condition. [&] lets it read `count` and, through // `this`, requests_. wait() only ever calls it with mutex_ locked, so // reading requests_ there is safe. The call means: // while (!(requests_ >= count)) { unlock, sleep until woken, relock } // with "unlock and start sleeping" done as one step, so a notify_all() // cannot slip in between and be missed. recorded_.wait(lock, [&] { return requests_ >= count; });} // wait() returned with mutex_ locked; `lock` unlocks it herestd::unique_lock, notstd::scoped_lock, becausewait()needs to unlock and lock again while it sleeps. Ascoped_lockcan only unlock when it is destroyed.wait(lock, condition)checks the condition first, and returns at once if it is already true. Otherwise it unlocks the mutex and starts sleeping as one step, so no thread that changes the data under the mutex can do so between the check and the sleep. When woken, it locks the mutex again and checks the condition again.- It checks again because a thread can wake for no reason. The
standard allows these spurious wakeups, and a notification can
also arrive after another change that does not meet this waiter’s
condition. Always wait with a condition, never with a bare
wait(lock). - The data is changed under the same mutex. If
record()changedrequests_without holdingmutex_, it could change it after the waiter checked the condition and before it slept, and the waiter would sleep through the change it was waiting for. Holding the mutex while changing the data is what prevents that. Sincerequests_is a plain integer, an unlocked change would also be a data race. - This waits forever if the count is never reached. There is no way to give up or be cancelled. Asynchronous work, cancellation, and shutdown covers waits that can be stopped.
Thread-safety contracts
Section titled “Thread-safety contracts”A user of a type cannot see its locks. The type’s header has to say what is allowed. Three answers cover most types:
| Contract | What callers may do | Examples on this site |
|---|---|---|
| Safe | Any members, from any number of threads at once. | HitCounter and RequestStats on this page. |
Safe for const use |
Any number of threads may call const members at once. Any other call needs every other thread kept away, by a lock the caller holds. |
The standard containers promise this. So do value types with no mutable members, no shared state behind pointers, and no statics, such as Money and the ID types in Strong types. |
Not safe, even for const |
One thread at a time, for every call. | The catalog with a mutable cache in Const correctness. |
Most classes should be safe for const use and leave locking to
their users. A class that locks inside every member pays for locks in
every program, including single-threaded ones, and its users usually
need a lock around several calls anyway. A class should be safe,
with its own mutex, when its whole purpose is to be shared, like the
statistics here, and when its invariant is something the users should
not have to know about.
What to write in the header of a type that is safe:
- the contract, in one line;
- which mutex guards which members;
- the invariant each mutex protects;
- which members can block, and for how long;
- what is not promised, such as sequences of calls.
A sequence of safe calls is not safe
Section titled “A sequence of safe calls is not safe”Each member of RequestStats is safe on its own. Two of them in a row
are not one step:
// Record a failure only while fewer than 100 have been recorded.if (stats.snapshot().failures < 100) { // another thread can record here, stats.record("/orders", latency, true); // so the limit can be passed}This code is illustrative and was not compiled.
Between the check and the action, other threads can record failures,
so the limit can be exceeded. This is check then act, a very
common race condition in code whose every call is “thread safe”. A
caller’s own lock fixes it only if every other caller takes the same
lock, and the class cannot make them. So if callers need that operation, the class has to offer it as one
member that checks and records under one lock, such as a
record_unless_failures_reach(limit, ...). Designing the class’s
interface around the operations its users must do in one step is part
of making it thread safe.
Running it
Section titled “Running it”The example starts four handler threads that record 1,000 requests each, half to each of two endpoints, with one in every hundred failing. The main thread waits for all 4,000, then reads:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Four handler threads each record 1,000 requests; the main thread waits// for all 4,000 with wait_for_requests, then reads the totals once every// handler has been joined.int main() { // Both objects live in main() and outlive every thread below, which is // what makes it safe for the threads to hold references to them. stats::RequestStats stats; stats::HitCounter page_views;
// Four threads, like four request handlers, record at the same time. // Which thread records first changes from run to run; the totals do not. { // std::jthread is a thread that joins (waits for itself to finish) // when it is destroyed. emplace_back starts each thread at once. std::vector<std::jthread> handlers; for (int worker = 0; worker < 4; ++worker) { // The lambda is the thread's body. It captures stats and // page_views by reference (&: shared with main) and worker by // value (each thread gets its own copy of the loop number). handlers.emplace_back([&stats, &page_views, worker] { for (int i = 0; i < 1000; ++i) { const bool failed = (i % 100 == 0); // 10 in every 1000 // Workers 0 and 2 use "/orders", workers 1 and 3 "/search". // 250us is 250 microseconds (a std::chrono literal). stats.record(worker % 2 == 0 ? "/orders" : "/search", 250us, failed); page_views.record(); } }); } // Returns once all 4000 are recorded; a handler may still be finishing // its last page_views.record(), so the totals below wait for the joins. stats.wait_for_requests(4000); std::cout << "all 4000 requests recorded\n"; } // each std::jthread joins its thread here
// Every thread has finished, so these reads see the final numbers. const stats::Snapshot now = stats.snapshot(); std::cout << "page views: " << page_views.hits() << '\n'; std::cout << "requests: " << now.requests << ", failures: " << now.failures << '\n'; // Reads the copy, with no lock: `now` belongs to this thread alone. // [endpoint, summary] unpacks each map entry (a structured binding). for (const auto& [endpoint, summary] : now.endpoints) { // microseconds divided by a count is still microseconds: 250 here. const auto average = summary.total_latency / summary.requests; std::cout << " " << endpoint << ": " << summary.requests << " requests, " << summary.failures << " failed, average " << average.count() << " us\n"; }}all 4000 requests recordedpage views: 4000requests: 4000, failures: 40 /orders: 2000 requests, 20 failed, average 250 us /search: 2000 requests, 20 failed, average 250 usstd::jthreadjoins its thread in its destructor, so leaving the block waits for every handler to finish. A plainstd::threadthat is destroyed while it can still be joined callsstd::terminate(). Asynchronous work, cancellation, and shutdown coversstd::jthread’s stop tokens.- The order in which threads record changes from run to run. The output does not, because it shows only totals, which do not depend on the order. A program whose output depends on the interleaving cannot have a fixed expected output.
page_views.hits()is read after the join, when no thread is recording. Read earlier, it could show any number up to 4,000.
Testing
Section titled “Testing”Tests of concurrent code run the same operations from several threads at once and then check what must be true whatever the interleaving was. The test harness is not thread safe, so the threads only record what they saw; every check runs on the main thread after they have joined.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false; LLD_CHECK_EQ(actual, expected) records one// if the two values are not equal, and prints both. They come from the// site's small test header, lld_test.hpp, and must run on the main thread.
// Sets up 8 threads that each record 5,000 requests at once, then proves// that all 40,000 arrived: no record() was lost to a race.LLD_TEST(no_record_is_lost_when_threads_record_at_once) { RequestStats stats; HitCounter hits; { std::vector<std::jthread> writers; for (int t = 0; t < 8; ++t) { writers.emplace_back([&stats, &hits, t] { for (int i = 0; i < 5000; ++i) { // Spreads the records over "/e0", "/e1", and "/e2", so // threads also race to create the same new endpoints. // Every tenth record (i = 0, 10, 20, ...) fails: 500 each. stats.record("/e" + std::to_string((t + i) % 3), 1us, i % 10 == 0); hits.record(); } }); } } // joined // Every writer has finished. 8 times 5,000 = 40,000 requests, and // 8 times 500 = 4,000 failures, whatever order the threads ran in. const Snapshot now = stats.snapshot(); LLD_CHECK_EQ(now.requests, 40'000); LLD_CHECK_EQ(now.failures, 4'000); LLD_CHECK_EQ(hits.hits(), 40'000);}
// Sets up one reader taking snapshots as fast as it can while 4 writers// record. Checks that every snapshot it took agrees with itself: its totals// equal the sum of its endpoints. With one atomic per number, as in TornStats,// this is the check that could catch a torn read.LLD_TEST(every_snapshot_is_consistent_while_others_write) { RequestStats stats; // Written by the reader thread, read by the main thread after the join. std::atomic<int> inconsistent{0}; std::atomic<int> snapshots{0}; // A std::latch is a one-time gate with a counter, here 1. wait() // blocks until count_down() has brought the counter to zero. std::latch reader_started{1}; { // A std::jthread whose body takes a std::stop_token can be asked to // stop: `stop` reports whether someone has called request_stop(). // [&] captures everything used inside by reference. std::jthread reader([&](std::stop_token stop) { reader_started.count_down(); // tells the main thread "running" // do ... while runs the body at least once, so even if the stop // request comes early, at least one snapshot is checked. do { const Snapshot now = stats.snapshot(); std::int64_t requests = 0; std::int64_t failures = 0; // Adds up the endpoints in this copy; entry.second is the // EndpointSummary part of each (name, summary) entry. for (const auto& entry : now.endpoints) { requests += entry.second.requests; failures += entry.second.failures; } if (requests != now.requests || failures != now.failures) { inconsistent.fetch_add(1); } snapshots.fetch_add(1); } while (!stop.stop_requested()); }); reader_started.wait(); // the writers start only once the reader runs { std::vector<std::jthread> writers; for (int t = 0; t < 4; ++t) { writers.emplace_back([&stats, t] { for (int i = 0; i < 5000; ++i) { // Even threads write "/a", odd threads "/b"; every // seventh record fails. stats.record(t % 2 == 0 ? "/a" : "/b", 1us, i % 7 == 0); } }); } } // writers joined; the reader's jthread asks it to stop, then joins } // (that happens here, when `reader` is destroyed) // Zero snapshots disagreed with themselves, and at least one was taken. LLD_CHECK_EQ(inconsistent.load(), 0); LLD_CHECK(snapshots.load() > 0);}How this code works: The snapshot test: who starts and stops when
The second test has three kinds of thread, and the order in which they start and stop is what makes it a fair test.
- The reader starts first. Constructing
readerstarts its thread. The main thread then callsreader_started.wait(), which blocks until the reader has calledcount_down(). So by the time any writer exists, the reader is already running its loop. - The reader loops. Each pass takes one snapshot (a copy made under
mutex_), adds up that copy’s endpoints with no lock, and compares the sums with the copy’s totals. A mismatch adds one toinconsistent. Every pass adds one tosnapshots. - Four writers record. Each writer makes 5,000 calls to
record(), even-numbered writers to"/a"and odd-numbered ones to"/b". Each call holdsmutex_for the whole update, so a snapshot is taken either before a given update or after it, never during it. - The inner block ends. The
writersvector is destroyed, and eachstd::jthreadin it joins its thread: the main thread waits until all 20,000 records are done. The reader is still looping. - The outer block ends. Now
readeris destroyed. Astd::jthreaddestructor first callsrequest_stop(), which makesstop.stop_requested()returntrue, and then joins. The reader finishes its current pass, sees the request at thewhile, and leaves the loop. - The checks run on the main thread, after every other thread has finished, because the test harness is not thread safe.
snapshots.load() > 0 can never fail, because a do ... while loop runs
its body at least once. What the test cannot control is how many of those
snapshots were taken while a writer was busy: that is up to the scheduler.
- No record is lost: 8 threads × 5,000 records give exactly 40,000. With the flawed counter this check would usually fail.
- Every snapshot is consistent: a reader thread takes snapshots as
fast as it can while 4 threads write, and counts any snapshot whose
totals disagree with its endpoints. A
std::latchmakes sure the reader has started before the writers do; how many of its snapshots overlap a write is still up to the scheduler. If the statistics used one atomic per number, asTornStatsdid, this is the check that could catch it. - The reader is a
std::jthreadthat loops until it is asked to stop. Its destructor asks it to stop, through thestd::stop_tokenit was given, and then joins it.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// Sets up a thread that waits for 100 requests, then records them from// the main thread. Proves the waiter is woken when the 100th arrives: no// wakeup is lost. If it were, this test would hang instead of failing.LLD_TEST(a_waiting_thread_wakes_when_the_count_is_reached) { RequestStats stats; std::atomic<bool> woke{false}; // A plain integer is safe here: joining the waiter makes its write // visible to the main thread, and nobody reads it before the join. std::int64_t seen = 0; // written by the waiter, read after it joins { // This body takes no std::stop_token, so the jthread's stop request // at the end of the block cannot cut the wait short. std::jthread waiter([&stats, &woke, &seen] { stats.wait_for_requests(100); // sleeps until 100 are recorded seen = stats.snapshot().requests; woke.store(true); }); std::this_thread::sleep_for(20ms); // give the waiter time to fall asleep // Each record() notifies; only the 100th makes the condition true. for (int i = 0; i < 100; ++i) { stats.record("/x", 1us, false); } } // joined: if the waiter never woke, this would never finish LLD_CHECK(woke.load()); LLD_CHECK(seen >= 100);}How this code works: One run of the wait test, step by step
This is the order the sleep is there to produce: the waiter goes to sleep before any request is recorded. The values come from the test.
| Step | Waiter thread | Main thread | requests_ |
|---|---|---|---|
| 1 | wait_for_requests(100) locks mutex_ |
sleeps for 20 ms | 0 |
| 2 | wait checks requests_ >= 100: false. It unlocks mutex_ and sleeps, as one step |
sleeping | 0 |
| 3 | asleep | record() number 1 locks, adds, unlocks, then calls notify_all() |
1 |
| 4 | may be woken; locks mutex_ again, finds requests_ still below 100, unlocks and sleeps again |
records 2, 3, … (each one may wake the waiter, which checks and sleeps again) | 2 to 99 |
| 5 | asleep or checking | record() number 100, then notify_all() |
100 |
| 6 | woken; locks mutex_, checks 100 >= 100: true. wait returns with mutex_ locked, and wait_for_requests unlocks it on the way out |
leaves the loop and reaches the end of the block, where waiter joins |
100 |
| 7 | snapshot() copies the stats; seen becomes 100; woke becomes true |
waiting in the join | 100 |
| 8 | finished | the join returns; both checks pass | 100 |
Two details matter:
- Step 2 is one step. If
waitunlocked and then, separately, went to sleep, arecord()and itsnotify_all()could run in the gap. The waiter would then sleep through the only notification it was going to get for that change. Unlocking and sleeping together, whilerecord()must hold the same mutex to changerequests_, closes that gap. - Step 4 may happen any number of times, including zero, and a
waiter may also wake with no notification at all (a spurious wakeup).
That is harmless, because
waitchecks the condition again every time it wakes and goes back to sleep while it is false.
If the waiter were slower to start than 20 ms, some records would
already have happened by step 2. If all 100 had, its first check would
be true and wait would return at once without sleeping. The test
would still pass, but it would not have tested the wakeup.
If the waiter never woke, the test would hang until its 120-second
CTest timeout failed it. That is how a lost wakeup shows up in a test
run: as a test that does not finish. The sleep makes it likely, not
certain, that the waiter is already asleep when the 100th record
arrives. Without it, the waiter usually finds the count already
reached and never sleeps, so a missing notify_all() would go
unnoticed.
What these tests cannot do:
- A passing run does not prove there is no race. A race happens only in some interleavings, and a run may never produce them. The flawed counter would pass a test that ran one thread at a time.
- TSan finds only the data races that happen in that run. The
examples are built and tested under the
tsanpreset as well as the others, so every test above also runs under TSan, and it reports nothing. That is evidence, not proof. - TSan cannot find a broken invariant, as
TornStatsshowed. Only a test that checks the invariant, like the snapshot test, can.
The page on testing concurrent code goes further.
The design at a glance
Section titled “The design at a glance”class stats::HitCounter
safe: one independent number
Data members
std::atomic<std::int64_t> hits_;
Member functions
void record() noexcept;std::int64_t hits() const noexcept;
class stats::RequestStats
safe: one mutex guards one invariant
Data members
mutable std::mutex mutex_;mutable std::condition_variable recorded_;std::int64_t requests_;guarded by mutex_std::int64_t failures_;guarded by mutex_std::map<std::string, EndpointSummary, std::less<>> endpoints_;guarded by mutex_
Member functions
void record(std::string_view endpoint, std::chrono::microseconds latency, bool failed);strongSnapshot snapshot() const;a consistent copyvoid wait_for_requests(std::int64_t count) const;blocks until reached
class stats::Snapshot
a value: shares nothing, needs no lock
Member functions
std::int64_t requests;std::int64_t failures;std::map<std::string, EndpointSummary, std::less<>> endpoints;
When this design fits, and when it does not
Section titled “When this design fits, and when it does not”A mutex inside the class fits when:
- The object exists to be shared, like statistics, a cache, or a registry, and every user would otherwise need the same lock.
- Its invariant spans several members that every operation must keep in step.
- The operations are short, so holding the lock for each one costs little.
Something else fits better when:
- The data does not need to be shared. Give each thread its own, or hand it from thread to thread, so that only one has it at a time. No lock is the cheapest lock.
- The data never changes after it is made. An object that is fully built before the threads start, and is only read afterwards, can be read by every thread with no lock, because reads alone do not race.
- Many events must be applied in order. One thread that owns the state and takes events from a queue keeps the domain classes single-threaded, as Quality constraints described, and State machines suggested for its connection.
- An operation must call slow or unknown code. Holding a lock while doing so blocks every other thread, and can deadlock. The page on deadlocks shows how to call out after unlocking.
Common mistakes
Section titled “Common mistakes”- “It is only a counter, a race is harmless.” A data race is
undefined behavior, not a small inaccuracy. Use a
std::atomic. - One atomic per value when the values must agree. No data race, and readers still see combinations that never existed.
- Locking the writes but not the reads. A read with no lock while another thread writes is a data race too.
- Returning a reference or pointer to guarded data. The lock ends when the function returns; the reference does not.
- Different mutexes for data in one invariant. A reader holding one of them can still see the other data half changed.
- Waiting on a condition variable without a condition, or changing the condition’s data without the mutex. The first can miss a notification sent before it waited, or return when nothing changed. The second can sleep through the very change it waits for.
- Doing slow work while holding the lock: logging, I/O, calling a callback. Every other thread waits for it.
- Calling a thread-safe class’s members in a sequence and assuming the sequence is one step. Offer the combined operation as a member.
When the requirements change
Section titled “When the requirements change”- “Show requests per minute, not since start.” The statistics gain
a current minute and a list of past ones. They are still one
invariant, so they stay under the same mutex;
record()moves to a new minute when the clock says so. - “Ten dashboards, each reading ten times a second.” Snapshots now
hold up handlers more often. Build one snapshot and keep it in a
std::shared_ptr<const Snapshot>, rebuilt at most a few times a second. A reader locks the mutex only long enough to copy that pointer, then reads the shared, immutable snapshot with no lock. The pointer itself still changes, so copying it and replacing it must both happen under the mutex. - “Recording is slow on a 64-core machine.” Every handler competes for one mutex. Give each thread its own statistics, each with its own mutex, and add them up when reading, after measuring that the lock is the cause.
- “Shutdown must not wait forever.”
wait_for_requestsneeds a way to give up, such as a time limit or a stop request. The planned page on asynchronous work, cancellation, and shutdown covers it.
Exercise
Section titled “Exercise”Exercise: Document a thread-safety contract
A search page keeps the last 10 search terms:
// Keeps the last 10 search terms, newest first.class RecentSearches {public: void add(std::string term); const std::vector<std::string>& terms() const { return terms_; } // Cached until the next add(). const std::string& most_common() const;
private: std::vector<std::string> terms_; mutable std::optional<std::string> most_common_; // the cache};This code is illustrative and was not compiled.
-
What thread-safety contract does this class have now? Write it as the one-line comment its header should carry, and say why.
-
The class is to be shared by every request handler. Change it so that its contract is safe. Which members change, and why?
-
A handler does this. Is it still a race condition after your change?
if (searches.terms().empty()) {searches.add("welcome");}This code is illustrative and was not compiled.
Show the explained answer
1. “Thread safety: not safe, even for const use; one thread at a
time.” Without the cache it would be safe for const use, like a
std::vector. But most_common() is const and writes the
mutable cache, so two threads that both call it can write
most_common_ at the same time: a data race, from two callers who
only read. A mutable member that const members write without a
mutex (or an atomic) takes away the const promise.
2.
// Thread safety: safe. Any number of threads may call any member at the// same time. Members return copies, never references into the guarded data.class RecentSearches {public: // Adds the newest term at the front and keeps at most 10. The whole // change, including clearing the cache, happens under one lock. void add(std::string term) { const std::scoped_lock lock(mutex_); terms_.insert(terms_.begin(), std::move(term)); // newest first if (terms_.size() > 10) { terms_.pop_back(); // drop the oldest, now the 11th } most_common_.reset(); // the cache no longer matches the terms }
// Returns a copy, made while locked: the caller's vector is its own. std::vector<std::string> terms() const { const std::scoped_lock lock(mutex_); return terms_; }
// Fills the cache on first use after an add(), then returns a copy of // it. Checking and filling the cache under one lock means two callers // cannot both fill it at the same time. std::string most_common() const { const std::scoped_lock lock(mutex_); if (!most_common_) { // true when the optional is empty most_common_ = compute_most_common(); // still under the lock } return *most_common_; // copies the cached string out }
private: std::string compute_most_common() const; // expects mutex_ to be held
mutable std::mutex mutex_; std::vector<std::string> terms_; // guarded by mutex_ mutable std::optional<std::string> most_common_; // guarded by mutex_};This class, with a body for compute_most_common and a main that
used it from three threads at once, was compiled with GCC 11.4 and
Clang 14 and run under ThreadSanitizer, which reported nothing.
- One mutex guards both members, because the cache must agree with
the terms. Clearing the cache in
add()and filling it inmost_common()both happen under it. terms()andmost_common()return copies. Returning references would let callers read the vector and the string after the lock was released, whileadd()changes them.- The mutex is
mutable, so theconstmembers can lock it.
3. Yes. It is no longer a data race, but it is still a race
condition: each call is safe, but two threads can both see an empty
list, and both add “welcome”. That is check then act. If it matters,
the class needs one member that checks and adds under one lock, such
as add_if_empty(std::string term).
Summary
Section titled “Summary”- A data race is two threads touching the same memory, at least one writing, at least one not atomic, with nothing ordering them. It is undefined behavior, not just lost updates.
- Classify the shared state first. A value that must agree with
nothing can be one
std::atomic. Values that must agree need one mutex that covers every read and write of all of them. Data that is not shared needs nothing. - Use
std::scoped_lockso that the mutex is always unlocked, and keep slow work outside the lock. - Return copies from a thread-safe class. A reference outlives the lock that protected it.
- Wait on a condition variable with a condition, and change the condition’s data under the same mutex.
- Write a thread-safety contract in every shared type’s header:
safe, safe for
constuse, or not safe. A sequence of safe calls is not safe; offer combined operations as members. - Test by running operations from several threads and checking what must hold afterwards, and run the tests under ThreadSanitizer. Neither proves the absence of races, and neither knows your invariants unless a test checks them.