我曾经在我的代码的某些部分看到 Sleep(0)
,其中一些无限/长 while
循环可用。我被告知它将使时间片可用于其他等待过程。这是真的? Sleep(0)
有什么意义吗?
最佳答案
根据 MSDN 的 Sleep 文档:
A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution.
要意识到的重要一点是,是的,这给了其他线程一个运行的机会,但是如果没有准备好运行,那么你的线程会继续 - 将 CPU 使用率保持在 100%,因为 某事 将始终运行。如果您的 while 循环在等待某些条件时只是在旋转,您可能需要考虑使用同步原语(如事件)休眠直到满足条件或休眠一小段时间以防止 CPU 耗尽。
关于c++ - sleep 的意义(0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3727420/