I want to sleep in a C11 program. Neither usleep (in unistd.h) nor nanosleep (in time.h) are declared with the -std=c11
option of both gcc (4.8.2) and clang (3.2).
A grep sleep /usr/include/*.h
doesn't reveal any other likely sleep candidates.
I need a sleep with at least millisecond precision.
How do I sleep in C11?
Use -std=gnu11
instead of -std=c11
(this works for both clang and gcc). This will cause the <time.h>
header to define nanosleep
.
Another alternative to nanosleep
, calling pselect
on a null file descriptor with a timeout, also only works with -std=gnu11
and not -std=c11
For an example of both:
#include <stdio.h>
#include <sys/select.h>
int main() // Compile with -std=gnu11 (and not -std=c11)
{
struct timespec ts1 = {
.tv_sec = 0,
.tv_nsec = 500*1000*1000
};
printf("first\n");
nanosleep(&ts1, NULL);
printf("second\n");
pselect(0, NULL, NULL, NULL, &ts1, NULL);
printf("third\n");
}
There in <windows.h>
a Sleep function and in <unistd.h>
an usleep function
that both of them are getting an unsigned int
as mili-seconds.
In the threads.h header there is the thrd_sleep function
int thrd_sleep( const struct timespec* time_point, struct timespec* remaining )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.