There is no portable solution that doesn't use busy waiting (i.e. a loop that just executes until a certain point in time is reached, which is bad because it hogs the CPU for no reason).
Therefore, in this case it would be better to write a small wait() function yourself that calls different functions depending on the platform.
xp_sleep.h:
Code:
void xp_sleep(unsigned int seconds);
void xp_millisleep(unsigned int milliseconds);
xp_sleep_win32.cpp:
Code:
#include <windows.h>
void xp_sleep(unsigned int seconds)
{
Sleep(seconds * 1000);
}
void xp_millisleep(unsigned int milliseconds)
{
Sleep(milliseconds);
}
xp_sleep_posix.cpp:
Code:
#define _POSIX_C_SOURCE 199309
#include <errno.h>
#include <time.h>
void xp_sleep(unsigned int seconds)
{
struct timespec ts = {
seconds,
0L
};
while(nanosleep(&ts, &ts) == -1 && errno == EINTR) {
}
}
void xp_millisleep(unsigned int milliseconds)
{
struct timespec ts = {
milliseconds / 1000,
(milliseconds % 1000) * 1000000L
};
while(nanosleep(&ts, &ts) == -1 && errno == EINTR) {
}
}
Then use the posix implementation for all Unix variants (including Mac OS X) and the win32 for Windows.
Usage:
Code:
#include "xp_sleep.h"
int main()
{
xp_sleep(5);
return 0;
}
Note: although this is the C++ forum, I've intentionally kept this code fully compatible with both C and C++.