Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::recursive_mutex — repeated locking by the same thread

std::recursive_mutex lets the same thread acquire the same mutex repeatedly. Other threads can acquire it only after every ownership level has been released. Each successful acquisition requires a separate unlock.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <mutex>
std::recursive_mutex m;
std::lock_guard<std::recursive_mutex> guard(m);

std::recursive_mutex, available in <mutex>, provides exclusive ownership with repeated acquisition by its owner. Unlike std::mutex, it lets the same thread call lock() again or successfully call try_lock() while already owning the mutex. This does not mean ownership is shared between threads.

Each successful acquisition increases the nesting level and requires one unlock(). Until the owner releases every level, another thread's lock() blocks and its try_lock() returns false. The maximum number of levels is unspecified: once it is reached, try_lock() fails and lock() throws std::system_error.

Use std::lock_guard<std::recursive_mutex> to pair each acquisition with release on scope exit, including exit through an exception. The mutex must outlive its guards. Destroying an owned mutex or terminating a thread while it still owns the mutex causes undefined behavior.

In the example, increment_twice() holds the outer lock, and each call to increment() temporarily adds another level. The guards release levels in reverse order. One thread is enough to demonstrate repeated acquisition and deterministic output; the example does not test thread contention. A recursive mutex does not replace a deliberate locking order for multiple mutexes.

Examples

#include <iostream>
#include <mutex>

class Counter {
    std::recursive_mutex mutex_;
    int value_ = 0;

public:
    void increment() {
        std::lock_guard<std::recursive_mutex> guard(mutex_);
        ++value_;
    }

    int increment_twice() {
        std::lock_guard<std::recursive_mutex> guard(mutex_);
        increment();
        increment();
        return value_;
    }
};

int main() {
    Counter counter;
    std::cout << counter.increment_twice() << '\n';
}

Result

2

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources