Is there an alternative for sleep() in C?

后端 未结 16 1981
无人及你
无人及你 2020-12-02 14:55

In traditional embedded programming, we will give a delay function like so:

for(i=0;i<255;i++)
   for(j=0;j<255;j++);

In the micropro

16条回答
  •  难免孤独
    2020-12-02 15:42

    One common mechanism is to use a select() that is guaranteed to time out, and specify the sleep time as the timeout:

    // Sleep for 1.5 sec
    struct timeval tv;
    tv.tv_sec = 1;
    tv.tv_usec = 500000;
    select(0, NULL, NULL, NULL, &tv);
    

    The select() is typically used to check a set of file descriptors and wait until at least one is ready to perform I/O. If none is ready (or, in this case, if no fds are specified), it will time out.

    The advantage of select() over a busy loop is that it consumes very little resources while sleeping, while a busy loop monopolizes the processor as much as permitted by its priority level.

提交回复
热议问题