Can scoped_lock lock a shared_mutex in read mode?
As pointed out by various commentators, who have read the implementation code of the C++ standard library: Yes, the use of a std::shared_mutex
wrapped inside a std::shared_lock()
as one of the arguments to std::scoped_lock()
is safe.
Basically, a std::shared_lock
forwards all calls to lock()
to lock_shared()
on the mutex.
std::shared_lock::lock -----------> mutex()->lock_shared(). // same for try_lock etc..
Another possible solution
std::shared_lock lk1(src.mutex, std::defer_lock);
std::unique_lock lk2(dst.mutex, std::defer_lock);
std::lock(lk1, lk2);
std::lock
is a function that accepts any number of Lockable
objects and locks all of them (or aborts with an exception, in which case they will all be unlocked).
std::scoped_lock
according to cppreference is a wrapper for std::lock
, with the added functionaliy of calling unlock()
on each Lockable object in its destructor. That added functionality is not required here, as std::shared_lock lk1
and std::unique_lock lk2
also work as lock guards, that unlock their mutexes, when they go out of scope.
Edit: various clarifications