Understanding C++'s BasicLockable Named Requirement

2025-09-19

In C++, the BasicLockable concept is a set of rules for types that can be used to achieve mutual exclusion. Put simply, it defines an object that can be locked and unlocked. The two main operations it must support are

lock()
This operation blocks the current thread until the lock is acquired. It's like a thread saying, "I'm going to use this resource, and I'll wait until it's free."

unlock()
This operation releases the lock, allowing other threads to acquire it. It's like a thread saying, "Okay, I'm done with the resource now. It's all yours."

A great example of a type that meets the BasicLockable requirements is std::mutex.

Even with a simple concept like this, it's easy to run into issues. Here are some of the most common problems and how to solve them.

This is probably the most famous concurrency problem. A deadlock occurs when two or more threads are waiting for each other to release a resource, and none of them can proceed.

Common Mistake
Let's say you have two std::mutex objects, m1 and m2.

// Thread 1
m1.lock();
// ... do some work ...
m2.lock();
// ... more work ...
m2.unlock();
m1.unlock();

// Thread 2
m2.lock();
// ... do some other work ...
m1.lock();
// ... more work ...
m1.unlock();
m2.unlock();

If Thread 1 locks m1 and then Thread 2 locks m2, both threads will then try to acquire the other mutex and get stuck forever.

Solution
Consistent Lock Order The best way to prevent this is to always acquire locks in the same order.

// Both Thread 1 and Thread 2 acquire m1, then m2
m1.lock();
m2.lock();
// ... do work ...
m2.unlock();
m1.unlock();

An even better solution is to use std::lock() which can lock multiple mutexes without causing a deadlock, as it acquires them all or none at all.

std::lock(m1, m2);
// ... do work ...
m2.unlock(); // You still need to unlock manually
m1.unlock();

This is a simple but critical error. If a thread acquires a lock and then forgets to release it, other threads will be blocked indefinitely. This can happen if an exception is thrown after the lock() call but before the unlock() call.

Common Mistake

void bad_function() {
    std::mutex m;
    m.lock();
    // What if an exception is thrown here?
    // The unlock() call will never be reached.
    m.unlock();
}

Solution
RAII (Resource Acquisition Is Initialization) The standard C++ library provides a wonderful solution for this
RAII. The std::lock_guard and std::unique_lock classes automatically handle locking and unlocking using their constructors and destructors.

std::lock_guard (Simple and Safe)

void good_function() {
    std::mutex m;
    std::lock_guard<std::mutex> lock(m); // Lock is acquired here
    // ... do work ...
    // The lock is automatically released when 'lock' goes out of scope,
    // even if an exception is thrown.
}

std::lock_guard is a BasicLockable replacement. It ensures that the lock is released no matter what.

std::unique_lock (More Flexible)
std::unique_lock offers more features than std::lock_guard, such as deferred locking, timed locking, and the ability to manually unlock.

void flexible_function() {
    std::mutex m;
    std::unique_lock<std::mutex> lock(m); // Lock is acquired here
    // ... do some work ...
    lock.unlock(); // You can manually unlock if you want
    // ... do some more work without the lock ...
    lock.lock(); // And re-lock it
}

For very simple, single-variable operations, using mutexes can be overkill and introduce performance overhead. Atomic operations are a more lightweight alternative. An atomic operation is one that is guaranteed to complete without interruption from other threads.

When to use Atomics
When you need to perform a single, indivisible operation on a variable, such as incrementing a counter.

Example with Atomics

#include <atomic>

std::atomic<int> counter{0};

void increment_counter() {
    // This is a single, atomic operation.
    // No need for a mutex!
    counter++;
}

This is much more efficient than locking a mutex just to increment a number.


cpp



C++ Ranges: adjacent_view::sentinel operator- Explained

First, let's quickly recap what a sentinel is in the context of C++ Ranges. A sentinel is an object that marks the end of a range


Understanding std::dynamic_extent in C++ Containers

std::dynamic_extent is a special constant value used with std::span. Think of std::span as a non-owning view over a contiguous sequence of objects


Understanding C++ std::thread::detach: Common Pitfalls and Safer Alternatives

The std::thread::detach function separates a thread from its "thread object, " which lets the thread run independently in the background



Demystifying std::formatter for C++ Chrono Dates

The std::formatter for std::chrono::year_month_day is great for creating clear, human-readable date strings. However, a few things can trip you up


Handling Missing std::hash for C++20 Chrono Types

The standard library doesn't provide a specialization for std::hash for std::chrono::year_month_weekday_last out of the box


The C++ Reader-Writer Timed Lock: try_lock_shared_for Explained

Here's a friendly breakdown of this function, common pitfalls, and some alternative approaches.This function is part of C++'s "Reader-Writer Lock" mechanism


C++ Memory Management: A Look at std::set_new_handler and its Modern Alternatives

std::set_new_handler is a powerful but often misunderstood tool in C++. It's part of the C++ standard library's memory management utilities


Effective Use of C++'s std::filesystem::space for Disk Management

At its core, std::filesystem::space is a function that gives you information about the disk space of a specified path. It returns a std::filesystem::space_info object


C++ Ranges: Understanding and Working with Iterators

The chunk_view::outer-iterator is an input or forward iterator, meaning it only supports operator++ for moving to the next chunk


C++ SIGABRT: Understanding and Handling Abort Signals

SIGABRT stands for "signal abort. " It's a signal that's sent to a process to cause it to abruptly terminate. In C++, this signal is often generated by the standard library's abort() function