I know the POSIX sleep(x)
function makes the program sleep for x seconds. Is there a function to make the program sleep for x milliseconds in C++?
C++ Linux – How to Sleep for Milliseconds
c++linuxsleep
Related Solutions
Yes - older POSIX standards defined usleep()
, so this is available on Linux:
int usleep(useconds_t usec);
DESCRIPTION
The usleep() function suspends execution of the calling thread for (at least) usec microseconds. The sleep may be lengthened slightly by any system activity or by the time spent processing the call or by the granularity of system timers.
usleep()
takes microseconds, so you will have to multiply the input by 1000 in order to sleep in milliseconds.
usleep()
has since been deprecated and subsequently removed from POSIX; for new code, nanosleep()
is preferred:
#include <time.h> int nanosleep(const struct timespec *req, struct timespec *rem);
DESCRIPTION
nanosleep()
suspends the execution of the calling thread until either at least the time specified in*req
has elapsed, or the delivery of a signal that triggers the invocation of a handler in the calling thread or that terminates the process.The structure timespec is used to specify intervals of time with nanosecond precision. It is defined as follows:
struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ };
An example msleep()
function implemented using nanosleep()
, continuing the sleep if it is interrupted by a signal:
#include <time.h>
#include <errno.h>
/* msleep(): Sleep for the requested number of milliseconds. */
int msleep(long msec)
{
struct timespec ts;
int res;
if (msec < 0)
{
errno = EINVAL;
return -1;
}
ts.tv_sec = msec / 1000;
ts.tv_nsec = (msec % 1000) * 1000000;
do {
res = nanosleep(&ts, &ts);
} while (res && errno == EINTR);
return res;
}
nanosleep
or clock_nanosleep
is the function you should be using (the latter allows you to specify absolute time rather than relative time, and use the monotonic clock or other clocks rather than just the realtime clock, which might run backwards if an operator resets it).
Be aware however that you'll rarely get better than several microseconds in terms of the resolution, and it always rounds up the duration of sleep, rather than rounding down. (Rounding down would generally be impossible anyway since, on most machines, entering and exiting kernelspace takes more than a microsecond.)
Also, if possible I would suggest using a call that blocks waiting for an event rather than sleeping for tiny intervals then polling. For instance, pthread_cond_wait
, pthread_cond_timedwait
, sem_wait
, sem_timedwait
, select
, read
, etc. depending on what task your thread is performing and how it synchronizes with other threads and/or communicates with the outside world.
Best Answer
In C++11, you can do this with standard library facilities:
Clear and readable, no more need to guess at what units the
sleep()
function takes.