How can i terminate a delay / wait condition

895 views Asked by At

I would like to know if there is any way to terminate a wait / delay condition.

I am using QTest::qwait(ms) for adding responsive delay in my code. Now i would like to terminate/break this delay. Something like, QTest::qWait(2000) will start a 2 sec delay, so what should i do to terminate this 2 second wait time?

Note: QTimer is not suitable for my code and i am using Qtest:qwait for adding the delay.

1

There are 1 answers

0
Rohan Prabhu On

The simple answer: You can't. The problem is that even if you use QTimer, and let's say a timeout of the QTimer is supposed to stop the waiting time, what would you connect your timeout signal to? Or what would a connected timeout slot execute or which function would it call to stop the wait?

Your best bet is to use the static method QThread::currentThread to obtain a pointer to the current QThread which you can then use to impose a wait condition on by using QThread::wait(2000) and then you can use an external thread to stop it on a condition. Let's take an example where in you want a thread to wait for 2s or till a processes increments to a counter till 9999999999. In that case, first you need to create your own class and then use it in your code:

class StopThread : public QThread {
private:
    QThread* _thread;

public:
    StopThread(QThread*);
    void run();
};

StopThread::StopThread(QThread* thread) {
    _thread = thread;
}

void StopThread::run() {
    //Do stuff here and see when a condition arises
    //for a thread to be stopped
    int i = 0;
    while(++i != 9999999999);
    _thread->quit();
}

And in your implementation:

QThread* thread = QThread::currentThread();
StopThread stopThread(thread);
stopThread->exec();
thread->wait(2000);

I understand that you need to do this with the testing method, but as far as I go, I can't think of another way. Hope it helps :)