September 12, 2026

A Mutex Does Not Make Your C++ Class Thread-Safe

A mutex can make every member function individually safe to call and still leave the class API fundamentally unsafe.

This happens because a mutex protects a critical section. It does not automatically protect the higher-level operation the caller is trying to perform.

Consider a queue with internally synchronized empty() and pop() functions:

if (!queue.empty()) {
    queue.pop();
}

empty() may lock a mutex correctly.

pop() may lock the same mutex correctly.

There may be no unsynchronized access to the underlying container at all.

And the code can still be wrong.

The operation the caller actually needs is not “check whether the queue is empty” followed by “remove an element”. The operation is:

check -> decide -> modify

If another thread can change the queue between those steps, the API did not give the caller an atomic operation.

This distinction matters in production C++ because data-race freedom and correct concurrent semantics are not the same thing. Thread safety has to be designed around invariants, state transitions and complete operations, not around the rule “put a mutex in every member function”.

Note

This article is not an argument against mutexes. Mutexes are often exactly the right synchronization primitive. The problem is choosing the wrong scope for the synchronization contract.

1 mutexdoesnotmakeyourclassthreadsafe

What the mutex actually guarantees


A mutex is not attached to an object or a piece of memory. It only provides synchronization where code actually locks it.

Consider a simple wrapper:

class PacketQueue
{
public:
    bool empty() const
    {
        std::scoped_lock lock(mutex_);
        return queue_.empty();
    }

    void push(Packet packet)
    {
        std::scoped_lock lock(mutex_);
        queue_.push_back(std::move(packet));
    }

    Packet pop()
    {
        std::scoped_lock lock(mutex_);

        if (queue_.empty()) {
            throw std::logic_error("pop from empty queue");
        }

        Packet packet = std::move(queue_.front());
        queue_.pop_front();
        return packet;
    }

private:
    mutable std::mutex mutex_;
    std::deque<Packet> queue_;
};

Assuming every access to queue_ uses mutex_, two threads cannot concurrently modify the std::deque without synchronization. That is important. We have prevented one class of undefined behaviour.

But look at the lifetime of the lock in empty().

The mutex is released before empty() returns to its caller.

That means the returned bool is a snapshot of a state that existed while the mutex was held. It is not a reservation. It does not prevent another thread from changing the queue immediately afterwards.

Useful mental model

A lock protects the relationship between operations performed while that lock is held. Once you release it, an observation of shared state may immediately become stale.

The queue bug has no data race


Assume the queue contains exactly one packet and two worker threads execute the same code:

if (!queue.empty()) {
    auto packet = queue.pop();
    process(packet);
}

A valid execution can look like this:

StepThread AThread BQueue
1empty() returns false1 packet
2empty() returns false1 packet
3pop() removes packetempty
4pop()empty

No two threads touched the underlying container while another thread held the mutex.

Every individual method respected the lock.

But Thread B made its decision using information that was no longer true.

Depending on the implementation, the second pop() may throw, hit an assertion, return an invalid value or trigger undefined behaviour in a lower-level container that requires the queue to be non-empty.

This is a logical race, not necessarily a data race

A race condition can exist even when every memory access is synchronized. The bug is in the ordering and meaning of operations, not in an unprotected load or store.

2 mutexdoesnotmakeyourclassthreadsafe

Design the API around the operation that must be atomic


The caller does not really want empty().

The caller wants:

“Give me the next packet if one exists.”

That should be one operation:

class PacketQueue
{
public:
    void push(Packet packet)
    {
        std::scoped_lock lock(mutex_);
        queue_.push_back(std::move(packet));
    }

    std::optional<Packet> tryPop()
    {
        std::scoped_lock lock(mutex_);

        if (queue_.empty()) {
            return std::nullopt;
        }

        Packet packet = std::move(queue_.front());
        queue_.pop_front();

        return packet;
    }

private:
    std::mutex mutex_;
    std::deque<Packet> queue_;
};

Now the check and the modification happen under one synchronization boundary.

if (auto packet = queue.tryPop()) {
    process(*packet);
}

The API expresses the real operation directly.

There is still concurrency. Another thread can win the race to the packet. But that race is now represented correctly in the result: one caller gets a packet and another caller gets std::nullopt.

That is a much stronger design than asking callers to construct an atomic operation from several separately synchronized fragments.

Production recommendation

When callers repeatedly write check -> decide -> modify around your class, ask whether that sequence should be one public operation.

Thread safety should be defined in terms of operations


“This class is thread-safe” is often too vague to be useful.

A better API contract answers questions such as:

  • Which operations may be called concurrently?
  • Which operations are atomic from the caller’s point of view?
  • Is a returned value a snapshot or does it reserve anything?
  • Can an operation block?
  • Can callbacks run while an internal lock is held?
  • Can references or iterators survive another mutation?
  • What happens during shutdown while other threads are waiting?

For operations intended to behave atomically, a useful concept is linearizability: each operation should appear to take effect at one point between its invocation and its return.

tryPop() has a natural linearization point while it owns the mutex and removes the element. The caller does not have to understand the internal lock to reason about the result.

Not every concurrent API has to provide linearizable semantics for everything. High-performance systems sometimes deliberately provide weaker consistency guarantees. But those guarantees should be explicit. “There is a mutex somewhere inside” is not a consistency model.

Protect invariants, not individual fields


The same problem appears in classes that do not look like queues.

Imagine a bandwidth budget shared by several worker threads:

class BandwidthBudget
{
public:
    std::size_t available() const
    {
        std::scoped_lock lock(mutex_);
        return available_;
    }

    void consume(std::size_t bytes)
    {
        std::scoped_lock lock(mutex_);

        if (bytes > available_) {
            throw std::logic_error("budget exceeded");
        }

        available_ -= bytes;
    }

private:
    mutable std::mutex mutex_;
    std::size_t available_{};
};

A caller may naturally write:

if (budget.available() >= packet.size()) {
    budget.consume(packet.size());
    send(packet);
}

Again, each member function is individually synchronized.

Again, two threads can both observe enough capacity before either consumes it.

The real invariant is:

available_ must never be consumed below zero

So expose the invariant-preserving operation:

bool tryConsume(std::size_t bytes)
{
    std::scoped_lock lock(mutex_);

    if (bytes > available_) {
        return false;
    }

    available_ -= bytes;
    return true;
}

The caller becomes simpler:

if (budget.tryConsume(packet.size())) {
    send(packet);
}

The important design change is not the use of bool. It is that the class now owns the complete state transition.

3 mutexdoesnotmakeyourclassthreadsafe

Getters and setters can expose impossible state transitions


Another common design smell is putting a lock around every getter and setter without asking which members form one invariant.

class Range
{
public:
    int min() const
    {
        std::scoped_lock lock(mutex_);
        return min_;
    }

    int max() const
    {
        std::scoped_lock lock(mutex_);
        return max_;
    }

    void setMin(int value)
    {
        std::scoped_lock lock(mutex_);
        min_ = value;
    }

    void setMax(int value)
    {
        std::scoped_lock lock(mutex_);
        max_ = value;
    }

private:
    mutable std::mutex mutex_;
    int min_{};
    int max_{100};
};

Every function locks correctly.

But suppose the invariant is:

min_ <= max_

Changing the range from [0, 100] to [200, 300] requires two calls:

range.setMin(200);
range.setMax(300);

Between those calls, another thread may observe [200, 100].

Even a single-threaded caller has temporarily broken the class invariant.

A better API changes the complete relationship:

struct RangeValue
{
    int min;
    int max;
};

class Range
{
public:
    void set(RangeValue range)
    {
        if (range.min > range.max) {
            throw std::invalid_argument("invalid range");
        }

        std::scoped_lock lock(mutex_);
        range_ = range;
    }

    RangeValue get() const
    {
        std::scoped_lock lock(mutex_);
        return range_;
    }

private:
    mutable std::mutex mutex_;
    RangeValue range_{0, 100};
};

This design improves both concurrency and the ordinary API. The state that belongs together is represented and changed together.

Design rule

Choose mutex boundaries from invariants and state transitions. Do not automatically choose them from the physical layout of individual members.

A thread-safe getter can return an unsafe reference


One of the more subtle mistakes is returning a reference or pointer to protected state after releasing the mutex.

class Configuration
{
public:
    const DeviceConfig& get() const
    {
        std::scoped_lock lock(mutex_);
        return config_;
    }

    void update(DeviceConfig config)
    {
        std::scoped_lock lock(mutex_);
        config_ = std::move(config);
    }

private:
    mutable std::mutex mutex_;
    DeviceConfig config_;
};

The lock in get() protects only the act of obtaining the reference.

The reference is used after the lock has already been released:

const auto& config = configuration.get();

use(config); // no Configuration mutex is held here

If another thread calls update() at the same time, the first caller can observe concurrent modification of the referred object.

The getter looked synchronized. The value it exposed was not.

Depending on the object and workload, better options include returning a copy:

DeviceConfig get() const
{
    std::scoped_lock lock(mutex_);
    return config_;
}

or publishing immutable snapshots:

std::shared_ptr<const DeviceConfig> get() const
{
    std::scoped_lock lock(mutex_);
    return config_;
}

with updates replacing the snapshot rather than mutating an object readers are already using.

Watch the lock boundary

Returning a reference, pointer, iterator, view or span into protected mutable state often lets the caller continue using that state after the synchronization that made access safe has ended.

4 mutexdoesnotmakeyourclassthreadsafe

Snapshot queries are useful, but they must be documented as snapshots


This does not mean functions such as size(), empty() or state() are useless in concurrent classes.

They can be useful for monitoring, metrics, diagnostics and decisions where approximate current state is enough.

const auto queuedPackets = queue.size();

metrics.setQueuedPackets(queuedPackets);

This is fine if size() means “return a synchronized snapshot of the current queue length”.

The mistake is using that snapshot as a precondition for a future modifying operation:

if (queue.size() < maxPending) {
    queue.push(packet);
}

If bounded capacity matters, the class should expose that operation directly:

bool tryPush(Packet packet)
{
    std::scoped_lock lock(mutex_);

    if (queue_.size() >= capacity_) {
        return false;
    }

    queue_.push_back(std::move(packet));
    return true;
}

The query is not inherently unsafe. Using a snapshot as if it reserved future state is unsafe.

Callbacks make lock scope much more dangerous


Production classes often need to notify another component after changing state.

The tempting implementation is:

void Connection::setState(State state)
{
    std::scoped_lock lock(mutex_);

    state_ = state;

    if (observer_) {
        observer_->onStateChanged(state_);
    }
}

The state transition is protected. But now arbitrary external code runs while the mutex is held.

The callback might:

  • call another Connection method that tries to acquire the same mutex;
  • take a different lock and create a lock-order cycle;
  • block on I/O;
  • dispatch work synchronously to another component;
  • destroy an object participating in the current operation;
  • throw an exception through code that expected only an internal state update.

A common pattern is to capture what must be notified while holding the lock, then call external code after releasing it:

void Connection::setState(State state)
{
    Observer* observer = nullptr;

    {
        std::scoped_lock lock(mutex_);

        state_ = state;
        observer = observer_;
    }

    if (observer != nullptr) {
        observer->onStateChanged(state);
    }
}

This removes one deadlock risk, but it introduces other design questions.

Is observer guaranteed to remain alive after the lock is released? Can another thread perform a second state transition before the first callback runs? If callback ordering matters, how is that ordering preserved?

There is no universal answer. The point is that callback execution is part of the concurrency contract. Moving it outside the mutex is often correct, but the surrounding lifetime and ordering semantics still need to be designed.

Do not fix reentrancy with recursive_mutex by reflex

A std::recursive_mutex may remove one self-deadlock, but it does not make reentrant state transitions logically correct. If callbacks can enter the object again halfway through an operation, your invariants still need to survive that execution.

Multiple objects make the atomicity problem larger


Sometimes the invariant spans more than one object.

Imagine two resource accounts:

if (source.balance() >= amount) {
    source.debit(amount);
    destination.credit(amount);
}

If balance(), debit() and credit() each lock their own object correctly, the transfer still is not atomic.

Two threads can both pass the balance check. Another operation can observe money removed from one account but not yet added to the other. An exception or early return can leave the operation half-complete.

If the invariant is “the transfer happens as one operation”, the synchronization boundary must cover both objects.

bool transfer(Account& source,
              Account& destination,
              Money amount)
{
    if (&source == &destination) {
        return true;
    }

    std::scoped_lock lock(source.mutex_,
                          destination.mutex_);

    if (source.balance_ < amount) {
        return false;
    }

    source.balance_ -= amount;
    destination.balance_ += amount;

    return true;
}

std::scoped_lock can acquire multiple mutexes using a deadlock-avoiding locking strategy. But access to those mutexes should usually stay inside an abstraction that owns the invariant rather than forcing every caller to coordinate private locks manually.

This is why concurrency often changes class boundaries. If correctness repeatedly requires locking several objects together, those objects may not actually own independent state.

5 mutexdoesnotmakeyourclassthreadsafe

Do not replace an invariant with several atomics


After discovering lock contention, the next temptation is often to replace several fields with std::atomic.

std::atomic<State> state_;
std::atomic<bool> connected_;
std::atomic<SessionId> sessionId_;

Each variable may now be accessed without a data race.

That does not automatically make combinations of those values consistent.

For example, suppose these three values must represent one coherent session:

connected_ == true
state_ == State::Ready
sessionId_ == current session

A reader performing three atomic loads can observe values originating from different state transitions unless the protocol has been designed specifically to prevent that.

Atomics are excellent for state that is genuinely independent or for carefully designed lock-free protocols. They are not a drop-in replacement for a mutex protecting a multi-field invariant.

Start from the invariant

If several values must change and be observed together, one mutex and one coherent state object are often easier to prove correct than several independent atomic variables.

Holding a mutex during blocking work is often the opposite problem


Once engineers understand that a compound operation needs one lock, it is easy to move too far in the other direction and keep the mutex held around everything.

void Session::send(Message message)
{
    std::scoped_lock lock(mutex_);

    if (state_ != State::Connected) {
        throw NotConnected{};
    }

    socket_.send(message); // may block
}

This may make the state check and the send look atomic, but now every operation that needs mutex_ waits for the transport.

If send() blocks because the peer is slow, another thread may be unable to:

  • request shutdown;
  • mark the session disconnected;
  • process a timeout;
  • update statistics or state;
  • perform another operation that does not actually conflict with network transmission.

This is where concurrency design becomes architectural rather than mechanical.

Possible designs include:

  • copying or acquiring a stable transport handle while under the lock and performing I/O afterwards;
  • serializing all transport operations through one event-loop thread;
  • placing outbound messages into a synchronized queue instead of sending synchronously;
  • giving the transport its own synchronization boundary separate from session state;
  • using a generation number or session token to detect that the state changed while work was in progress.

The right answer depends on the architecture. What matters is recognizing that “hold the mutex for the whole operation” is not always practical when the operation contains slow external work.

Thread safety does not solve object lifetime


A class may synchronize every member correctly and still be destroyed while another thread is using it.

PacketQueue* queue = getQueue();

std::thread worker([queue] {
    while (running()) {
        queue->tryPop();
    }
});

// Somewhere else:
delete queue;

The internal mutex does nothing to protect the lifetime of the mutex itself or the object containing it.

This matters especially for:

  • background worker threads;
  • asynchronous callbacks;
  • timer handlers;
  • event-loop tasks;
  • observers stored by another subsystem.

The destruction contract must define how work stops, how waiting threads wake up and when it becomes impossible for another operation to enter the object.

A queue used by worker threads, for example, often needs more than push() and tryPop(). It may need explicit close() semantics so blocked consumers can terminate cleanly.

Important distinction

Internal synchronization protects operations on a live object. Ownership and shutdown design determine whether the object is still alive when those operations happen.

A production queue usually needs lifecycle semantics too


Once a queue becomes part of a worker system, “thread-safe push and pop” is rarely the complete contract.

You often need to answer:

  • What happens when the queue is empty?
  • Does a consumer wait or return immediately?
  • Can producers push after shutdown starts?
  • Does shutdown drain pending work or discard it?
  • How does a blocked consumer learn that no more work will arrive?
  • Can multiple consumers wait concurrently?

A more realistic interface might look like:

class PacketQueue
{
public:
    bool push(Packet packet);

    std::optional<Packet> tryPop();

    std::optional<Packet> waitPop();

    void close();

    std::size_t size() const; // snapshot only
};

The names expose semantic operations instead of low-level container primitives.

For example, waitPop() can define that it returns a packet when one becomes available or std::nullopt once the queue has been closed and drained.

That is a concurrency contract a caller can reason about.

6 mutexdoesnotmakeyourclassthreadsafe

Exception safety is part of the invariant too


std::scoped_lock and std::lock_guard make mutex release exception-safe. If the function throws, the lock object is destroyed and the mutex is released.

That does not automatically make the protected state exception-safe.

Consider a state transition involving several changes:

void Registry::replace(DeviceId id, Device device)
{
    std::scoped_lock lock(mutex_);

    devices_.erase(id);
    devices_.emplace(id, std::move(device));
}

If the insertion can fail after the old device has been removed, the mutex still unlocks correctly, but the logical operation may have left the registry in a state the API did not intend.

Concurrency does not remove ordinary exception-safety requirements. In fact, it makes them more important because another thread can observe the state immediately after the failing operation releases the mutex.

Where possible, prepare potentially failing work before committing the protected state transition, or use operations with the exception guarantees your invariant requires.

Why ThreadSanitizer may tell you everything is fine


ThreadSanitizer is one of the most useful tools for debugging concurrent C++ programs. It can detect many unsynchronized memory accesses that are extremely difficult to reproduce manually.

A typical Clang or GCC sanitizer build uses flags such as:

-fsanitize=thread -g -O1 -fno-omit-frame-pointer

Then run the relevant test or executable under the instrumented build.

But ThreadSanitizer is not a proof that your API is logically thread-safe.

Go back to the original queue example:

if (!queue.empty()) {
    queue.pop();
}

If both functions lock correctly, there may be no data race for ThreadSanitizer to report.

The problem is that the program made an invalid assumption about what the result of empty() guarantees after the function returns.

A clean ThreadSanitizer run is necessary evidence, not a correctness proof

Sanitizers are excellent at finding certain implementation races. They cannot infer every business invariant or determine that two individually synchronized calls were supposed to form one transaction.

Make the bad interleaving deterministic in a test


Concurrency bugs are much easier to understand when a test forces the interesting interleaving instead of hoping the scheduler eventually produces it.

For the broken empty() + pop() API, a test can deliberately place both threads between the check and the modification:

PacketQueue queue;
queue.push(Packet{});

std::barrier checked{2};

auto worker = [&] {
    const bool hasPacket = !queue.empty();

    checked.arrive_and_wait();

    if (hasPacket) {
        queue.pop();
    }
};

std::jthread first{worker};
std::jthread second{worker};

Both threads are forced to complete empty() before either continues to pop().

With one packet in the queue, both can observe hasPacket == true. Only one can actually remove the packet.

This test is much more useful than inserting arbitrary sleeps:

std::this_thread::sleep_for(10ms); // not a synchronization strategy

A sleep changes timing. A barrier establishes the exact ordering needed to demonstrate the faulty contract.

7 mutexdoesnotmakeyourclassthreadsafe

Add invariant checks where the state is actually protected


Assertions are especially useful in concurrent code when they check state while the relevant lock is held.

void Queue::checkInvariant() const
{
    // mutex_ must already be held by the caller.

    assert(size_ <= capacity_);
    assert(readIndex_ < capacity_);
    assert(writeIndex_ < capacity_);
}

Then call the invariant check after state-changing operations in development or diagnostic builds.

The important detail is where the assertion runs. Reading several protected fields without the lock just to “check the invariant” can introduce a new race in the diagnostic code itself.

For more complex state machines, also consider recording a monotonically increasing generation or transition sequence in diagnostics:

logDebug("session transition",
         "generation", generation_,
         "from", previousState,
         "to", state_);

This makes it easier to reconstruct whether a caller acted on stale state or whether two logically related operations were interleaved.

Stress tests still have value


Deterministic tests cover interleavings you already understand. Stress tests help expose the ones you did not anticipate.

For a concurrent queue or state machine, useful stress testing can include:

  • several producers and consumers running concurrently;
  • randomized operation sequences;
  • frequent start/stop transitions;
  • forced shutdown while workers are blocked;
  • allocation failures or injected operation failures where practical;
  • running the same scenario thousands of times under ThreadSanitizer.

Occasional std::this_thread::yield() calls in dedicated stress-test builds can also increase scheduling variation, but they should be treated as test perturbation rather than synchronization.

Common failure modes


  • Locking every public function and declaring the class thread-safe. The caller may still need an atomic sequence spanning several functions.
  • Using a snapshot as a reservation. Results from empty(), size(), available() or state() can become stale immediately after the function returns.
  • Returning references or iterators into protected mutable state. The caller keeps the handle after your mutex has been released.
  • Protecting fields instead of invariants. Two separately locked members may need to change together.
  • Calling external code while holding a mutex. Callbacks, virtual functions and blocking I/O can introduce reentrancy, latency and deadlocks.
  • Using several atomics for one logical state. Individual atomicity does not automatically produce a coherent multi-field snapshot.
  • Ignoring lifetime. A mutex cannot protect an object that has already been destroyed.
  • Assuming ThreadSanitizer proves correctness. A logical check-then-act race can be completely data-race-free.
  • Splitting locks too early for performance. More mutexes create more states that can be observed independently and more lock-order relationships to maintain.
  • Fixing reentrancy with recursive_mutex. Allowing the same thread back into the object does not prove that entering halfway through another operation preserves the invariant.

Start with a coarse correct lock before optimizing it


There is a tendency in performance-sensitive C++ to treat a single mutex protecting several fields as unsophisticated.

But one mutex has a major engineering advantage: it gives the protected invariant one clear synchronization boundary.

Splitting that mutex into three locks can improve concurrency, but it also forces you to answer new questions:

  • Which operations need one lock?
  • Which operations need two?
  • In what order are they acquired?
  • Can another thread observe state between the updates?
  • Which fields are really independent?

Those may be worthwhile trade-offs if profiling proves the original lock is a bottleneck.

Do not pay the correctness complexity before you have evidence that you need the performance.

Production recommendation

Begin with the simplest synchronization scheme that preserves the full invariant. Measure contention on the real workload. Split synchronization only when you can define which invariants become independent.

A practical API review checklist


When reviewing a class used from several threads, I would ask these questions before looking at how many mutexes it contains:

  1. What are the invariants? Identify relationships between fields, not only the fields themselves.
  2. What are the real caller operations? Look for repeated check -> decide -> modify sequences outside the class.
  3. Which operations must appear atomic? Define their consistency guarantees explicitly.
  4. Which queries are only snapshots? Name or document them so callers do not treat them as reservations.
  5. Does anything escape the lock? Check returned references, pointers, iterators, spans, views and callbacks.
  6. Does anything external run under the lock? Look for callbacks, virtual calls, logging backends, I/O and cross-component calls.
  7. Can several objects participate in one invariant? If yes, define who coordinates the operation and the lock order.
  8. What happens during destruction and shutdown? Ensure workers stop, blocked operations wake and no callback can enter a dead object.
  9. What happens when an operation throws or fails halfway through? The protected state still needs a valid invariant when the lock is released.
  10. How will the contract be tested? Combine sanitizer runs, deterministic interleaving tests, stress tests and invariant checks.
8 mutexdoesnotmakeyourclassthreadsafe

The key idea


If you remember only one thing, remember this:

Thread safety belongs to the API contract

A mutex can make individual member functions data-race-free. It does not automatically make sequences of those functions atomic, preserve multi-field invariants, protect returned references, solve callback reentrancy or keep the object alive.

Good concurrent APIs expose the operation the caller actually needs.

Instead of empty() followed by pop(), expose tryPop().

Instead of available() followed by consume(), expose tryConsume().

Instead of several setters that temporarily break an invariant, update the complete state as one operation.

The mutex is still important. But it comes after the design question:

What must other threads be unable to observe halfway through?

Once you can answer that, you can choose the synchronization boundary that actually protects the contract.