睡眠/纳米睡眠是否可以通过忙碌的等待方案来工作? [英] Does sleep/nanosleep work by utilizing a busy wait scheme?

查看:129
本文介绍了睡眠/纳米睡眠是否可以通过忙碌的等待方案来工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道内部如何实现睡眠/纳米睡眠吗?考虑以下代码:

I am wondering how is sleep/nanosleep internally implemented? Consider this code:

{ // on a thread other than main() thread
  while(1)
  {
    //do something
    sleep(1);
  }
}

CPU是否会进行持续的上下文切换以检查是否完成了1秒的睡眠(即内部繁忙等待).

would the CPU be doing constant context switching to check if sleep of 1 sec is done (i.e. an internal busy wait).

我怀疑这种方式是否有效,效率太低.但是,它如何工作?

I doubt it works this way, too much inefficiency. But then how does it work?

同样的问题也适用于纳米睡眠.

Same question applies to nanosleep.

注意:如果这是特定于实现/操作系统的,那么我怎么可能实现一种不会导致上下文连续切换的更有效的方案?

Note: If this is implementation/OS specific, then how can I possibly implement a more efficient scheme that doesn't lead to a constant context switching?

推荐答案

此处不保证确切的实现,但是您可以期望一些属性.

Exact implementation is not guaranteed here but you can expect some properties.

通常,sleep(3)非常不准确,并且由于甚至可以使用SIGALM(信号)来实现Linux的"man sleep 3"状态.因此,这绝对不是性能.绝对也不是自旋锁,因此不会占用大量CPU.

Usually sleep (3) is quite inaccurate and as Linux 'man sleep 3' states could be even implemented using SIGALM (signals). So it is definitely not about performance. It is definitely not about spin locks too so cannot be CPU intensive.

nanosleep是完全不同的动物,即使使用自旋锁也可以实现.更为重要的是,至少在Linux nanosleep中,第2节中的内容是系统调用,因此至少它应该包括切换到内核模式.您真的需要它的高分辨率吗?

nanosleep is quite different animal which could be implemented even using spinlocks. Which is more important, at least in Linux nanosleep man is in section 2 which stands it is system call so at least it should include switch to kernel mode. Do you really need its high resolution?

更新

如您所见,我确实建议使用select(),因为man select 3指出:

As I see your comment I do recommend select() usage as man select 3 states:

   #include <stdio.h>
   #include <stdlib.h>
   #include <sys/time.h>
   #include <sys/types.h>
   #include <unistd.h>

   int
   main(void)
   {
       fd_set rfds;
       struct timeval tv;
       int retval;

       /* Watch stdin (fd 0) to see when it has input. */
       FD_ZERO(&rfds);
       FD_SET(0, &rfds);

       /* Wait up to five seconds. */
       tv.tv_sec = 5;
       tv.tv_usec = 0;

       retval = select(1, &rfds, NULL, NULL, &tv);
       /* Don't rely on the value of tv now! */

       if (retval == -1)
           perror("select()");
       else if (retval)
           printf("Data is available now.\n");
           /* FD_ISSET(0, &rfds) will be true. */
       else
           printf("No data within five seconds.\n");

       exit(EXIT_SUCCESS);
   }

如果您需要在某个事件中在线程中睡眠,并且该事件可以链接到文件描述符,这是经过验证的机制.

It is proven mechanics if you need to sleep in thread for some event and this event could be linked to file descriptor.

这篇关于睡眠/纳米睡眠是否可以通过忙碌的等待方案来工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆