c++ - sleep 的意义(0)

标签 c++ visual-c++ process sleep

我曾经在我的代码的某些部分看到 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/

相关文章:

c++ - 在 C++ 中使用 std::getline() 获取带空格的输入

c++ - Swig 和引用计数的 C++ 类

c++ - 在带有 msvc11 的静态类析构函数中使用 std::system_category()

c++ - 为什么这个仿函数 ("lambda") 会发出奇怪的警告?

linux - Oracle 表单 : How to check if oracle forms 11g process is running?

同一运算符的 C++ 多个运算符重载

c++ - 为什么 std::forward 会丢弃 constexpr-ness?

c++ - 错误 C2440 : '=' : cannot convert from 'char [5]' to 'char [20]'

java - 进程间共享线程

linux - 将所有 OS 进程绑定(bind)到一个 CPU