Home > Back-end >  std::unique_lock and std::shared_lock in same thread - shouldn't work, but does?
std::unique_lock and std::shared_lock in same thread - shouldn't work, but does?

Time:06-28

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?

CodePudding user response:

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 ).

CodePudding user response:

I've tried your sample code on "Visual Studio 2022" (17.2.5) and mutexes and locks are working as expected : shared_lock is locked on constructor.

  • Related