Synchronization: mutex, atomic & condition_variable
The data race
int counter = 0;
// two threads each run: for (1000 times) ++counter;
++counter is read–add–write. Threads interleave → updates get lost; it's undefined behaviour. Result might be 1,437 instead of 2,000.
std::mutex + std::lock_guard ✅ (<mutex>)
std::mutex m;
void deposit(double x) {
std::lock_guard<std::mutex> lock(m); // locks now, unlocks at scope end (RAII)
balance += x;
}
Only one thread at a time runs the locked section (critical section). Keep it short.
std::unique_lock— like lock_guard but can unlock/relock (needed for condition variables)std::scoped_lock(m1, m2)(C++17) — locks several mutexes without deadlock
Deadlock ⚠️
Thread A locks m1 then waits for m2; thread B locks m2 then waits for m1 → both wait forever. Fix: always lock in the same order, or use std::scoped_lock.
std::atomic<T> (<atomic>)
For single variables (counters, flags):
std::atomic<int> counter{0};
++counter; // atomic read-modify-write, no lock needed
counter.load(); counter.store(5); counter.fetch_add(2);
std::condition_variable — waiting for something
std::unique_lock lock(m);
cv.wait(lock, [] { return !queue.empty() || done; }); // sleeps until notified AND condition true
Producer: change the data under the lock, then cv.notify_one() / notify_all().
Always wait with a predicate (spurious wakeups happen).
The producer–consumer pattern
A thread-safe queue: producers push tasks, consumers wait and pop them. The core of thread pools, download managers and logging systems.
Tools
Compile with -fsanitize=thread (ThreadSanitizer) to detect races.
Example
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
#include <vector>
class Account {
public:
void deposit(long long paisa) {
std::lock_guard<std::mutex> lock(m_); // one thread at a time
balance_ += paisa;
}
long long balance() const {
std::lock_guard<std::mutex> lock(m_);
return balance_;
}
private:
mutable std::mutex m_;
long long balance_ = 0;
};
template <typename T>
class SafeQueue {
public:
void push(T value) {
{ std::lock_guard<std::mutex> lock(m_); q_.push(std::move(value)); }
cv_.notify_one();
}
void close() {
{ std::lock_guard<std::mutex> lock(m_); closed_ = true; }
cv_.notify_all();
}
bool pop(T& out) { // false when closed and empty
std::unique_lock<std::mutex> lock(m_);
cv_.wait(lock, [this] { return !q_.empty() || closed_; });
if (q_.empty()) return false;
out = std::move(q_.front());
q_.pop();
return true;
}
private:
std::mutex m_;
std::condition_variable cv_;
std::queue<T> q_;
bool closed_ = false;
};
int main() {
Account acc;
std::atomic<int> deposits{ 0 };
{
std::vector<std::jthread> tellers;
for (int t = 0; t < 4; ++t)
tellers.emplace_back([&] {
for (int i = 0; i < 10'000; ++i) { acc.deposit(100); ++deposits; }
});
}
std::cout << "deposits: " << deposits << ", balance: Rs. " << acc.balance() / 100 << " (expected 40000)\n";
SafeQueue<int> jobs;
std::atomic<long long> processed_sum{ 0 };
std::atomic<int> processed_count{ 0 };
{
std::vector<std::jthread> workers;
for (int w = 0; w < 3; ++w)
workers.emplace_back([&] {
int job;
while (jobs.pop(job)) { processed_sum += job; ++processed_count; }
});
for (int j = 1; j <= 100; ++j) jobs.push(j); // producer
jobs.close();
}
std::cout << "workers processed " << processed_count << " jobs, sum " << processed_sum << '\n';
std::mutex a, b;
int transfers = 0;
{
std::jthread t1([&] { for (int i = 0; i < 1000; ++i) { std::scoped_lock lk(a, b); ++transfers; } });
std::jthread t2([&] { for (int i = 0; i < 1000; ++i) { std::scoped_lock lk(b, a); ++transfers; } });
} // scoped_lock avoids deadlock despite opposite order
std::cout << "transfers without deadlock: " << transfers << '\n';
return 0;
}
/* Output:
deposits: 40000, balance: Rs. 40000 (expected 40000)
workers processed 100 jobs, sum 5050
transfers without deadlock: 2000
*/