[Qt-interest] wait / sleep outside of QThread
Matthias Pospiech
matthias.pospiech at gmx.de
Wed Aug 19 10:18:28 CEST 2009
I have long ago set up a function delay which is constantly looking for
the elapsed time.
inline void delay(long ms) // time in ms
{
QTime time;
time.start();
while (time.elapsed()<ms);
}
This works fine, but is killing CPU usage for nothing. I can not use
Signal/Slots, because that would mean a complete rewrite of most of my
functions.
The typicall usage is something like
void foo()
{
dowhatever();
delay(100);
donext();
}
or
while(ClassDerivedFromQThread.isRunning()) { delay(50); }
In this list I found some different approaches:
1) -------------------------------------
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.
2) -------------------------------------
#include <qwaitcondition.h>
QWaitCondition sleep;
sleep.wait(2000); // two seconds
3) -------------------------------------
QTime dieTime = QTime::currentTime().addSecs(2);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEvents, 100);
Is anything of this recommanded?
Matthias
More information about the Qt-interest-old
mailing list