2

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?

3
  • 1
    You have only one thread... Commented Jun 27, 2022 at 15:22
  • 2
    @kaba A thread locking a std::shared_mutex that 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." Commented Jun 27, 2022 at 15:26
  • @FrançoisAndrieux Al right, thanks, that was the part I missed (so the sentence I quoted now seems a bit misleading to me). The fact you hinted on, also holds the other way around (i.e. is stated for lock_shared as well). Commented Jun 27, 2022 at 15:32

1 Answer 1

7

Also from cppreference: "If lock_shared is called by a thread that already owns the mutex in any mode (exclusive or shared), the behavior is undefined."

You have UB; the toolchain is not required to diagnose this, though it might if you enabled your stdlib's debug mode (_GLIBCXX_DEBUG for libstdc++).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.