Significance of Sleep(0)

2019-01-23 00:59发布

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)?

8条回答
乱世女痞
2楼-- · 2019-01-23 01:31

I'm afraid I can't improve on the MSDN docs here

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.

Windows XP/2000: A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution. This behavior changed starting with Windows Server 2003.

Please also note (via upvote) the two useful answers regarding efficiency problems here.

查看更多
Rolldiameter
3楼-- · 2019-01-23 01:31

Sleep(0) is a powerful tool and it can improve the performance in certain cases. Using it in a fast loop might be considered in special cases. When a set of threads shall be utmost responsive, they shall all use Sleep(0) frequently. But it is crutial to find a ruler for what responsive means in the context of the code.

I've given some details in https://stackoverflow.com/a/11456112/1504523

查看更多
登录 后发表回答