Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::shared_lock — managing shared lock ownership

std::shared_lock from <shared_mutex> manages shared lock ownership using RAII. It supports concurrent reading by multiple threads, but does not provide the exclusive ownership needed to modify shared data.

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

Syntax

#include <mutex>
#include <shared_mutex>

// Acquire shared ownership immediately:
std::shared_lock<Mutex> guard(m);

// Alternatively, defer acquisition:
// std::shared_lock<Mutex> guard(m, std::defer_lock);

std::shared_lock<Mutex> manages shared ownership of a lock; it is not the mutex itself. Mutex must meet the Cpp17SharedLockable requirements. The object is movable but not copyable. Its associated mutex must exist for the guard's entire remaining lifetime, even while the guard does not own the lock.

Construction with just a mutex calls lock_shared() and may block. Destruction calls unlock_shared() if the guard owns the lock. std::defer_lock postpones acquisition, std::try_to_lock attempts acquisition without waiting, and std::adopt_lock requires the current thread to hold shared ownership already. Use owns_lock() or conversion to bool to check an acquisition attempt.

For std::shared_mutex, multiple threads can hold shared ownership simultaneously; exclusive ownership cannot coexist with it. Follow a consistent protocol: reads under std::shared_lock, writes under an exclusive lock such as std::unique_lock. Shared ownership does not enforce constness and does not itself protect concurrent writes by readers.

unlock() releases an owned lock, whereas release() only detaches the mutex from the guard—it does not unlock it. Timed operations require a mutex meeting Cpp17SharedTimedLockable; std::shared_mutex is insufficient. The example deliberately uses one thread: writing finishes before reading, and both scopes demonstrate automatic lock release.

Examples

#include <iostream>
#include <mutex>
#include <shared_mutex>

int main() {
    std::shared_mutex mutex;
    int value = 0;
    {
        std::unique_lock<std::shared_mutex> writer(mutex);
        value = 42;
    }
    {
        std::shared_lock<std::shared_mutex> reader(mutex);
        std::cout << std::boolalpha
                  << reader.owns_lock() << ' ' << value << '\n';
    }
}

Result

true 42

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