Solved mutex/unique_lock/try_lock_for
-
Can someone please explain for me why this code @
try_lock_for
throws "Resource deadlock avoided" or what I"ve done wrong?{ std::mutex mutex; std::unique_lock<std::mutex> locker(mutex); qDebug()<<"work"; } { std::timed_mutex tMutex; std::unique_lock<std::timed_mutex> lock(tMutex); lock.try_lock_for(std::chrono::milliseconds(100)); qDebug()<<"explode before here"; }
-
Hi,
Where is that code called from ?
-
windows
Ubuntu
-
With mutex's in a class instance as members also:
-
Hi, I think because you trying to lock tMutex twice, easiest is remove the first lock, for example:
{ std::timed_mutex tMutex; std::unique_lock<std::timed_mutex> lock(tMutex,std::defer_lock); lock.try_lock_for(std::chrono::milliseconds(100)); qDebug()<<"no longer explode before here"; }
-
Yes, thanks that's great. I just had another developer (family member) give me this exact code so thanks to you and him, this is working as expected.
Not sure I understand why it tries to lock tMutex twice. Maybe I'll understand fully another time. I'm happy I'm out of the woods though. Thanks all.
-
I think I understand the double lock now.
std::unique_lock<std::timed_mutex> lock(tMutex); // RAII lock attempt lock.try_lock_for(std::chrono::milliseconds(100)); // another lock request == resource deadlock
This defer lock commands the unique lock to not lock on construction, so then I can command locking behavior myself.