ConcurrencyC++verifiedVerified

Mutex / Lock Pattern in C++

Guarantee that only one thread at a time can access a shared resource by requiring threads to acquire an exclusive lock before proceeding.

How to Implement the Mutex / Lock Pattern in C++

1Step 1: Shared resource protected by a mutex

class Counter {
    int value_ = 0;
    std::mutex mu_;
public:
    void increment() {
        std::lock_guard lock(mu_);
        ++value_;
    }

    int get() const { return value_; }
};

2Step 2: Multiple threads safely increment the counter

int main() {
    Counter counter;
    std::vector<std::thread> threads;

    for (int i = 0; i < 10; ++i) {
        threads.emplace_back([&counter] {
            for (int j = 0; j < 1000; ++j)
                counter.increment();
        });
    }

    for (auto& t : threads) t.join();

    std::cout << "Final count: " << counter.get() << "\n";
    // Always 10000 thanks to mutex protection
}

Mutex / Lock Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Mutex / Lock Pattern in the Real World

A single-occupancy public restroom with a door latch is a perfect mutex. The latch (lock) ensures only one person (thread) occupies the restroom (critical section) at a time. Anyone who finds the door locked must wait outside; when the occupant leaves and unlatches the door, one waiting person may enter.