Skip to main content
Be Bitwise
C++Concurrency in C++

Synchronisation in C++

C++ wraps its synchronisation primitives in RAII, sidestepping the worst pthread bug: the forgotten unlock that turns into a deadlock at 3am. C++ locks ride on object lifetimes instead.

std::mutex and std::lock_guard

The simplest synchronisation is a mutex with an RAII lock:

cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
class BankAccount {
double balance_ = 0;
mutable std::mutex mutex_;
public:
void deposit(double amount) {
std::lock_guard<std::mutex> lock(mutex_);
balance_ += amount;
}
double balance() const {
std::lock_guard<std::mutex> lock(mutex_);
return balance_;
}
};
int main() {
BankAccount account;
std::vector<std::thread> threads;
for (int i = 0; i < 10; i++) {
threads.emplace_back([&account]() {
for (int j = 0; j < 1000; j++) {
account.deposit(1.0);
}
});
}
for (auto& t : threads) t.join();
std::cout << "Balance: " << account.balance() << "\n";
return 0;
}

std::lock_guard grabs the mutex in its constructor and drops it in its destructor. The lock comes off no matter how the scope ends — return, exception, anything. A whole genre of bug just disappears.

Key Concept

The mutable keyword lets you lock the mutex inside const member functions. That's fine: the mutex guards logical state, and acquiring it doesn't change anything an observer can see.

std::unique_lock

std::unique_lock is more flexible than lock_guard. It supports:

  • Deferred locking
  • Timed locking
  • Manual unlock/relock
  • Moving between scopes
cpp
#include <mutex>
#include <chrono>
std::mutex mtx;
void flexible_locking() {
// Deferred lock - does not lock immediately
std::unique_lock<std::mutex> lock(mtx, std::defer_lock);
// Do some work without the lock
prepare_data();
// Now lock
lock.lock();
modify_shared_state();
lock.unlock();
// Do more work without the lock
process_results();
// Lock again for final update
lock.lock();
final_update();
// Automatically unlocked when lock goes out of scope
}
void try_locking() {
std::unique_lock<std::mutex> lock(mtx, std::try_to_lock);
if (lock.owns_lock()) {
// Got the lock
} else {
// Someone else holds it; do something else instead of waiting
}
}
std::timed_mutex tmtx;
void timed_locking() {
// Calls tmtx.try_lock_for(): waits up to 50 ms, then gives up
std::unique_lock<std::timed_mutex> lock(tmtx, std::chrono::milliseconds(50));
if (!lock.owns_lock()) {
// Timed out
}
}

try_to_lock never waits at all. A genuine timeout needs a std::timed_mutex, since plain std::mutex has no try_lock_for.

The runner here can't start threads, but the RAII half of the story needs none. lock_guard and unique_lock work with any type that has lock() and unlock(), so this program hands them a mutex that narrates what's done to it. Predict where the unlock lands when deposit(-5) throws.

Try itRemove the final lock.lock() in batch_job() and check the destructor no longer unlocks: unique_lock only releases a mutex it currently owns.
C++ (GCC 9.2.0)

std::condition_variable

Condition variables in C++ work similarly to pthreads but with RAII locks:

cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
template <typename T>
class ThreadSafeQueue {
std::queue<T> queue_;
mutable std::mutex mutex_;
std::condition_variable cv_;
public:
void push(T value) {
{
std::lock_guard<std::mutex> lock(mutex_);
queue_.push(std::move(value));
}
cv_.notify_one();
}
T pop() {
std::unique_lock<std::mutex> lock(mutex_);
cv_.wait(lock, [this]{ return !queue_.empty(); });
T value = std::move(queue_.front());
queue_.pop();
return value;
}
bool try_pop(T& value, std::chrono::milliseconds timeout) {
std::unique_lock<std::mutex> lock(mutex_);
if (!cv_.wait_for(lock, timeout, [this]{ return !queue_.empty(); })) {
return false;
}
value = std::move(queue_.front());
queue_.pop();
return true;
}
};

That lambda you hand to cv_.wait replaces the explicit while loop from the pthreads playbook. The runtime evaluates it before sleeping and after each wakeup, so spurious wakeups vanish on their own.

std::shared_mutex (C++17)

std::shared_mutex implements a read-write lock:

cpp
#include <shared_mutex>
#include <string>
#include <unordered_map>
class ThreadSafeCache {
std::unordered_map<std::string, std::string> data_;
mutable std::shared_mutex mutex_;
public:
std::string get(const std::string& key) const {
std::shared_lock<std::shared_mutex> lock(mutex_);
auto it = data_.find(key);
return (it != data_.end()) ? it->second : "";
}
void set(const std::string& key, const std::string& value) {
std::unique_lock<std::shared_mutex> lock(mutex_);
data_[key] = value;
}
};

Many threads can hold a shared_lock at once for reads. A unique_lock for writes wants the place to itself.

Avoiding Deadlocks with std::scoped_lock

When several mutexes need locking together, std::scoped_lock (C++17) acquires them in a deadlock-free order:

cpp
#include <mutex>
class Account {
double balance_;
std::mutex mutex_;
friend void transfer(Account& from, Account& to, double amount);
};
void transfer(Account& from, Account& to, double amount) {
// Locks both mutexes without deadlock
std::scoped_lock lock(from.mutex_, to.mutex_);
from.balance_ -= amount;
to.balance_ += amount;
}

Without it, thread A moving money from account 1 to 2 while thread B moves money from 2 to 1 is a textbook deadlock. scoped_lock runs a deadlock-avoidance algorithm under the covers.

Here's the version without it. Picture transfer(alice, bob, 10) and transfer(bob, alice, 5) running at the same moment on two threads:

cpp
void transfer(Account& from, Account& to, double amount) {
std::lock_guard<std::mutex> a(from.mutex_);
std::lock_guard<std::mutex> b(to.mutex_);
from.balance_ -= amount;
to.balance_ += amount;
}

Draw who holds what and who's waiting for what, and the problem is a loop. Solid arrows are locks held, dotted arrows are locks wanted:

std::scoped_lock breaks the loop by never blocking on one mutex while it sits on the other. If it can't get the second, it lets go of the first and tries again, so the solid-plus-dotted pair for a single thread never forms.

Does it always deadlock?

No, which is what makes it nasty. It only hangs when both threads take their first lock before either takes its second: thread 1 holds Alice's mutex and waits for Bob's, thread 2 holds Bob's and waits for Alice's, and neither will ever let go. Most runs slip through, so the bug can survive testing and show up under production load. std::scoped_lock, or always locking in a fixed order such as by address, removes the cycle.

std::call_once

When you need thread-safe one-shot initialisation:

cpp
#include <mutex>
class Database {
static std::once_flag init_flag_;
static Database* instance_;
Database() { /* expensive initialisation */ }
public:
static Database& instance() {
std::call_once(init_flag_, []() {
instance_ = new Database();
});
return *instance_;
}
};
std::once_flag Database::init_flag_;
Database* Database::instance_ = nullptr;

Cheaper than a mutex once initialisation has run: no synchronisation overhead on subsequent calls. For a singleton like this one you don't need call_once at all, though. Since C++11 a function-local static Database db; inside instance() is initialised exactly once, thread-safely, the first time control reaches it, and unlike the new above it gets destroyed at exit.

Summary of Lock Types

Lock TypeUse Case
lock_guardSimple scoped locking
unique_lockNeed to unlock/relock, use with condition_variable
shared_lockRead access with shared_mutex
scoped_lockLock multiple mutexes safely

Guidelines

  1. Reach for lock_guard first. It's the lightest tool that does the job.
  2. Pick unique_lock when condition variables or manual control are in play.
  3. Pick scoped_lock whenever multiple mutexes are involved.
  4. Keep critical sections tight. Never hold a lock across I/O.
  5. Consider lock-free alternatives on hot paths (next lesson).

Challenges

Create a counter class that uses std::mutex to safely increment from two threads. Each thread increments 100000 times. Print the final value.

C++ (GCC 9.2.0)