How to know if a thread is waiting for a lock?



  • Consider the code below:
    @
    void MyThread::run()
    {
    sMutex.lock();
    mHasLock = true;
    SomeTask();
    sMutex.unlock();

    emit done();
    }
    @
    sMutex is the static member of MyThread. Say, I have a 100 MyThreads, one of them is executing and the other 99 are waiting for a lock on this static mutex. At this instance the UI is closed, causing the destructor of MyThread to be called, I require that the thread that is executing wait() for completion and the other 99 are terminated safely. I have done it in the following way, But the documentation of terminate says that it is not safe to use it; is it safe in my scenario?

    @
    MyThread::~MyThread()
    {
    if (!mHasLock) {
    // This thread is waiting for the lock, safe to terminate.
    this->terminate();
    }
    if(this->isRunning()) {
    this->quit();
    this->wait();
    }
    }
    @



  • I'd recommend to do
    @if (!mHasLock) {
    return;
    }@



  • Personally, doing it your way, I'd make mHasLock static also to ensure that only one thread can have mHasLock == true at any given point in time.

    Alternatively, you can look at QMutex::trylock() for a different approach (checking whether a thread has or hasn't got a lock).

    To get back to your core issue, terminate() CAN be used, it just doesn't have any built-in clean-up or safety checks, so the warning in the API docs is to ensure that YOU are sure :)



  • Not sure "static" advice is really good. In this case you will not know which thread is in lock (and in dtor you will terminate ALL threads). If you want to do it static for locking then mutex is already here.



  • [quote author="Denis Kormalev" date="1307282404"]Not sure "static" advice is really good. In this case you will not know which thread is in lock (and in dtor you will terminate ALL threads). If you want to do it static for locking then mutex is already here.[/quote]

    Sorry, that was a very silly mistake to make on my part and what you say makes perfect sense, I just never considered it that way. Thanks for the input!


Log in to reply
 

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