简体   繁体   中英

std::shared_mutex recursive protection by thread_local storage

The idea is to use the std::shared_mutex all right, but protect deadlocks in case that std::shared_mutex::lock() for exclusive access is called by the same thread.

For example:

std::shared_mutex m;
void f2()
{
  m.lock();
}
void f1()
{
   m.lock();
   f2();
}

f1() would lock because std::shared_mutex cannot be called recursively. For this I have two options: Either to use my own tlock of read-write mutex which uses Windows Mutex which supports recursive locking, or to use this sort of a locking function based on a thread_local variable:

thread_local bool LockedStuff = 0;
void Lock(std::function<...> f)
{
    if (LockedStuff)
        {
         f(...);
         return;
        }
    LockedStuff = 1;
    m.lock();
    f(...);
    m.unlock();
    LockedLinks = 0;
}

The question is, is there anything I'm missing that can go wrong with the above implementation? Thanks a lot.

That you don't RAII your mutex and thread local variable. If exception is called inside the function your mutex will be forever locked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM