Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what can I use to replace sleep and usleep in my Qt app?

I'm importing a portion of existing code into my Qt app and noticed a sleep function in there. I see that this type of function has no place in event programming. What should I do instead?

UPDATE: After thought and feedback I would say the answer is: call sleep outside the GUI main thread only and if you need to wait in the GUI thread use processEvents() or an event loop, this will prevent the GUI from freezing.

like image 319
yan bellavance Avatar asked Dec 23 '09 01:12

yan bellavance


4 Answers

It isn't pretty but I found this in the Qt mailing list archives:

The sleep method of QThread is protected, but you can expose it like so:

class SleeperThread : public QThread
{
public:
    static void msleep(unsigned long msecs)
    {
        QThread::msleep(msecs);
    }
};

Then just call:

SleeperThread::msleep(1000);

from any thread.

However, a more elegant solution would be to refactor your code to use a QTimer - this might require you saving the state so you know what to do when the timer goes off.

like image 175
Rob Avatar answered Oct 12 '22 06:10

Rob


It is not necessary to break down the events at all. All I needed to do was to call QApplication::processEvents() where sleep() was and this prevents the GUI from freezing.

like image 20
yan bellavance Avatar answered Oct 09 '22 23:10

yan bellavance


I don't recommend sleep in a event based system but if you want to ...
You can use a waitcondition, that way you can always interrupt the sleep if neccesary.

//...
QMutex dummy;
dummy.lock();
QWaitCondition waitCondition;
waitCondition.wait(&dummy, waitTime);
//...
like image 9
TimW Avatar answered Oct 12 '22 06:10

TimW


The reason why sleep is a bad idea in event based programming is because event based programming is effectively a form on non-preemptive multitasking. By calling sleep, you prevent any other event becoming active and therefore blocking the processing of the thread.

In a request response scenario for udp packets, send the request and immediately wait for the response. Qt has good socket APIs which will ensure that the socket does not block while waiting for the event. The event will come when it comes. In your case the QSocket::readReady signal is your friend.

If you want to schedule an event for some point of time in the future, use QTimer. This will ensure that other events are not blocked.

like image 6
doron Avatar answered Oct 12 '22 06:10

doron