实施繁忙循环的最佳方法? [英] Best way to implement busy loop?
问题描述
实现忙循环的最佳方法是什么?如果我错了纠正我吗?
What is the best way to implement the busy loop ? correct me if i am wrong ?
while (1); // obviously eats CPU.
while (1) { sleep(100); } // Not sure if it is the correct way ?
推荐答案
要无限等待,对于信号(还有什么),有一个pause()
系统调用.您必须将其放入循环中,因为每次传递信号时它都会返回(总是将-1并且errno设置为EINTR):
To do an infinite wait, for a signal (what else) there is the pause()
system call. You'll have to put it in a loop, as it returns (always with -1 and errno set to EINTR) every time a signal is delivered:
while (1)
pause();
奇怪的是,这是AFAIK唯一记录为总是失败的POSIX函数.
As a curious note, this is, AFAIK the only POSIX function documented to always fail.
更新:感谢dmckee,在下面的注释中,sigsuspend()
也总是失败.它的作用与pause()
相同,但是对信号更友好.区别在于它具有参数,因此除了EINTR
之外,它还会因EFAULT
失败.
UPDATE: Thanks to dmckee, in the comments below, sigsuspend()
also fails always. It does just the same as pause()
, but it is more signal-friendly. The difference is that it has parameters, so it can fail with EFAULT
in addition to EINTR
.
这篇关于实施繁忙循环的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!