Why is it possible to acquire two different locks on a std::shared_mutex?
The following code
#include <shared_mutex> #include <iostream> int main(int /*argc*/, char * /*argv*/[]) { std::shared_mutex mut; std::unique_lock<std::shared_mutex> ulock{mut}; if(ulock) std::cout << "uniqe_lock is bool true\n"; if(ulock.owns_lock()) std::cout << "uniqe_lock owns lock\n"; std::shared_lock<std::shared_mutex> slock{mut}; if(slock) std::cout << "shared_lock is bool true\n"; if(slock.owns_lock()) std::cout << "shared_lock owns lock\n"; } when compiled with a g++ 9.4.0 (current available on Ubuntu 20.04.1)
g++ -std=c++17 mutex.cpp outputs all cout lines. I.e. the thread acquires both the unique_lock and the shared_lock. As I understand cppreference on the shared_mutex, acquiring the second lock should fail while the first one is still alive.
"Within one thread, only one lock (shared or exclusive) can be acquired at the same time."
What do I miss here? Why can the shared_lock be acquired even with the previous unique_lock still active?
std::shared_mutexthat it already has a lock on is Undefined Behavior. See here : "If lock is called by a thread that already owns the mutex in any mode (shared or exclusive), the behavior is undefined."lock_sharedas well).