Documentation Home

The std::shared_lock class template provides a lock ownership wrapper for shared-ownership locks. The type of mutex being locked is specified by the template parameter Mutex, which must meet the SharedLockable requirements. In general, the specified mutex is locked for shared ownership in the constructor and unlocked in the destructor, though additional constructors and member functions are provided to allow other possibilities. This provides a means of locking a mutex for a block of code and ensuring that the mutex is unlocked when the block is left, whether that is by running off the end, by the use of a control flow statement such as break or return, or by throwing an exception. All instantiations of std::shared_lock are suitable for use with the Lockable parameter for the std::condition_variable_any wait functions.

All instantiations of std::shared_lock meet the Lockable requirements and the TimedLockable requirements.

Instances of std::shared_lock are MoveConstructible and MoveAssignable, but not CopyConstructible or CopyAssignable.

template <class Mutex>
class shared_lock
{
public:
    typedef Mutex mutex_type;

    shared_lock();
    explicit shared_lock(mutex_type& m);
    shared_lock(mutex_type& m, adopt_lock_t);
    shared_lock(mutex_type& m, defer_lock_t);
    shared_lock(mutex_type& m, try_to_lock_t);

    template<typename Clock,typename Duration>
    shared_lock(
        mutex_type& m,
        std::chrono::time_point<Clock,Duration> const&
        absolute_time);

    template<typename Rep,typename Period>
    shared_lock(
        mutex_type& m,
        std::chrono::duration<Rep,Period> const&
        relative_time);

    ~shared_lock();

    shared_lock(shared_lock const& ) = delete;
    shared_lock& operator=(
        shared_lock const& ) = delete;

    shared_lock(shared_lock&& );
    shared_lock& operator=(shared_lock&& );

    void swap(shared_lock&& other);

    void lock();
    bool try_lock();
    template<typename Rep, typename Period>
    bool try_lock_for(
        std::chrono::duration<Rep,Period> const&
        relative_time);
    template<typename Clock, typename Duration>
    bool try_lock_until(
        std::chrono::time_point<Clock,Duration> const&
        absolute_time);
    void unlock();

    explicit operator bool() const;
    bool owns_lock() const;
    Mutex* mutex() const;
    Mutex* release();
};
Header

#include <shared_mutex>

See Also