简体   繁体   English

C11中的睡眠功能

[英]sleep function in C11

I want to sleep in a C11 program. 我想睡在C11程序中。 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). usleep(在unistd.h中)和nanosleep(在time.h中)都没有使用gcc(4.8.2)和clang(3.2)的-std=c11选项声明。

A grep sleep /usr/include/*.h doesn't reveal any other likely sleep candidates. grep sleep /usr/include/*.h没有透露任何其他可能的睡眠候选者。

I need a sleep with at least millisecond precision. 我需要一个至少毫秒精度的睡眠。

How do I sleep in C11? 我怎么在C11睡觉?

Use -std=gnu11 instead of -std=c11 (this works for both clang and gcc). 使用-std=gnu11而不是-std=c11 (这适用于clang和gcc)。 This will cause the <time.h> header to define nanosleep . 这将导致<time.h>标头定义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 nanosleep另一种替代nanosleep ,在带有超时的空文件描述符上调用pselect ,也只适用于-std=gnu11而不是-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 <windows.h>有一个Sleep函数,在<unistd.h>一个usleep函数

that both of them are getting an unsigned int as mili-seconds. 他们两个都得到了一个unsigned int作为mili-seconds。

In the threads.h header there is the thrd_sleep function 在threads.h头文件中有thrd_sleep函数

int thrd_sleep( const struct timespec* time_point, struct timespec* remaining )

http://en.cppreference.com/w/c/thread/thrd_sleep http://en.cppreference.com/w/c/thread/thrd_sleep

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM