写Linux应用时用到睡眠函数,比如sleep,usleep,但是将应用移植到Windows系统却是编译错误。本文解决Linux与Windows睡眠函数的兼容性问题。
#include <QCoreApplication>
#ifdef Q_OS_WIN32
#include <windows.h>
#define sleep(sec) Sleep(sec * 1000)
#define msleep(msec) Sleep(msec)
#else
#include <unistd.h>
#define msleep(msec) usleep(msec * 1000)
#endif
static void usleep(unsigned long usec)
{
HANDLE timer;
LARGE_INTEGER interval;
interval.QuadPart = -(10 * usec);
timer = CreateWaitableTimer(NULL, TRUE, NULL);
SetWaitableTimer(timer, &interval, 0, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);
}
#include <QCoreApplication>
#ifdef Q_OS_WIN32
#include <windows.h>
#define sleep(sec) Sleep(sec * 1000)
#define msleep(msec) Sleep(msec)
static void usleep(unsigned long usec)
{
HANDLE timer;
LARGE_INTEGER interval;
interval.QuadPart = -(10 * usec);
timer = CreateWaitableTimer(NULL, TRUE, NULL);
SetWaitableTimer(timer, &interval, 0, NULL, NULL, 0);
WaitForSingleObject(timer, INFINITE);
CloseHandle(timer);
}
#else
#include <unistd.h>
#define msleep(msec) usleep(msec * 1000)
#endif
int main(int argc, char *argv[])
{
sleep(1);
msleep(100);
usleep(1000);
}