QThread always stuck in wait

575 views Asked by At

I am trying to use QThread to call a function in another thread without having the UI to freeze. I am using QT5.11.2 on both windows and linux.

Everything works fine on windows but the wait() function for QThread never returns no matter what.

I use RHEL7 on linux

Here is what I am doing:

void MainWidget::configure_click(double value)
{
    QThread *myThread = QThread::create([this, value]{ Configure(value); });
    dsoThread->setObjectName("My Configure Thread");
    QObject::connect(myThread, &QThread::finished, [](){ qDebug()<< "Configure Thread has finished";});  //  This is never printed

    myThread->start();
    myThread->wait();  //  Never returns from this
    myThread->quit();
    myThread->deleteLater();
}

My Configure function prints its start and finish and both lines are being printed on run time

void MainWidget::Configure(double value)
{
    qDebug() << QThread::currentThread() << " started";
    
    //  Code to execute

    qDebug() << QThread::currentThread() << " finished";
}

I even read that quit() forces the thread to stop, so just for testing I tried switching quit() and wait() like so

    myThread->quit();
    myThread->wait();  //  Never returns from this either
    myThread->deleteLater();

I even tried looping the isRunning() function instead of wait() but I got the same results

    while(myThread->isRunning())  //  Same goes for !isFinished()
    {
        //  Do nothing
    }

It seems like no matter what the thread never knows that it was finished.

What can I do to either solve this problem or to check why this is happening?

1

There are 1 answers

2
mugiseyebrows On
  1. You haven't start()ed the thread.
  2. myThread->wait(); in gui thread waits for thread to terminate so it blocks gui thread event loop, so you lose all benifints of threading this way and might as well just do Configure(value); without threading.

Documentation says:

wait() and the sleep() functions should be unnecessary in general, since Qt is an event-driven framework. Instead of wait(), consider listening for the finished() signal. Instead of the sleep() functions, consider using QTimer.