睡眠的意义(0) [英] Significance of Sleep(0)

查看:177
本文介绍了睡眠的意义(0)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾经在我的代码的某些部分看到 Sleep(0),其中一些无限/长 while 可用。我被告知,它将使时间片可用于其他等待进程。这是真的?对于 Sleep(0)有什么意义吗?

I used to see Sleep(0) in some part of my code where some infinite/long while loops are available. I was informed that it would make the time-slice available for other waiting processes. Is this true? Is there any significance for Sleep(0)?

推荐答案

MSDN的睡眠文档:


值为零导致线程
放弃其剩余时间
切片到任何其他线程
准备运行。如果没有其他
线程准备运行,函数
立即返回,线程
继续执行。

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。

The important thing to realize is that yes, this gives other threads a chance to run, but if there are none ready to run, then your thread continues -- leaving the CPU usage at 100% since something will always be running. If your while loop is just spinning while waiting for some condition, you might want to consider using a synchronization primitive like an event to sleep until the condition is satisfied or sleep for a small amount of time to prevent maxing out the CPU.

这篇关于睡眠的意义(0)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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