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";    
        }
    
    

  • Lifetime Qt Champion

    Hi,

    Where is that code called from ?



  • windows
    windows

    Ubuntu
    Ubuntu



  • With mutex's in a class instance as members also:
    mutex's as members



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


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.