Sleep problem without QThread class
-
how to make my program sleep for 100 ms without using Qthread class??
-
You either use QTest
@
QTest::qSleep(100); // no event processing
QTest::qWait(100); // event processing
@
or you use QWaitCondition / QMutex
@
QWaitCondition waitCondition;
QMutex mutex;waitCondition.wait(&mutex, 100);
@
or you use QThread.
@
class Thread : public QThread
{
public:
static void msleep(int ms)
{
QThread::msleep(ms);
}
};Thread::msleep(100);
@However, having to do so in an event-driven application is usually a clear indicator for a broken design.
-
[quote author="broadpeak" date="1325618245"]
Hm... What about the (pure virtual) run() function?[/quote]It is indeed virtual, but not pure. The default implementation simply calls exec() (which doesn't even matter in our case, as the thread isn't started). QThread::msleep() causes the current thread to sleep.
-
On unix like machins (including the Mac):
@
#include <unistd.h>// sleep for 5 seconds
sleep(5);// sleep for another 5 seconds (5,000,000 microseconds)
usleep(5000000);
@On Windows:
@
// sleep for 5 seconds (5000 milliseconds)
Sleep(5000);
@Or copy the implementation of QTest::qSleep():
@
#ifdef Q_OS_WIN
#include <windows.h> // for Sleep
#else
#include <time.h>
#endifvoid mySleep(int ms)
{
if(ms <= 0)
return#ifdef Q_OS_WIN
Sleep(uint(ms));
#else
struct timespec ts = { ms / 1000, (ms % 1000) * 1000 * 1000 };
nanosleep(&ts, NULL);
#endif
}
@