有人可以用 Sleep(1) 解释这个有趣的行为吗? [英] Could someone explain this interesting behaviour with Sleep(1)?

查看:20
本文介绍了有人可以用 Sleep(1) 解释这个有趣的行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当被要求等待 1 毫秒时,我正在测试各种 win32 API 调用将等待多长时间.我试过了:

I was testing how long a various win32 API calls will wait for when asked to wait for 1ms. I tried:

::睡眠(1)
::WaitForSingleObject(handle, 1)
::GetQueuedCompletionStatus(handle, &bytes, &key, &overlapped, 1)

::Sleep(1)
::WaitForSingleObject(handle, 1)
::GetQueuedCompletionStatus(handle, &bytes, &key, &overlapped, 1)

我使用 QueryPerformanceCounter 和 QueryPerformanceFrequency 检测经过的时间.大多数情况下,经过的时间大约为 15 毫秒,这是 Internet 上预期和记录的.然而,在短时间内等待大约需要 2 毫秒!!!它持续发生几分钟,但现在又回到 15 毫秒.我没有使用 timeBeginPeriod() 和 timeEndPeriod 调用!然后我在另一台机器上尝试了相同的应用程序,等待时间持续约 2 毫秒!两台机器都装有 Windows XP SP2,硬件应该相同.有什么可以解释为什么等待时间差异如此之大的原因吗?TIA

I was detecting the elapsed time using QueryPerformanceCounter and QueryPerformanceFrequency. The elapsed time was about 15ms most of the time, which is expected and documented all over the Internet. However for short period of time the waits were taking about 2ms!!! It happen consistently for few minutes but now it is back to 15ms. I did not use timeBeginPeriod() and timeEndPeriod calls! Then I tried the same app on another machine and waits are constantly taking about 2ms! Both machines have Windows XP SP2 and hardware should be identical. Is there something that explains why wait times vary by so much? TIA

推荐答案

Thread.Sleep(0) 将让任何具有相同优先级的线程执行.Thread.Sleep(1) 将让任何具有相同或更低优先级的线程执行.

Thread.Sleep(0) will let any threads of the same priority execute. Thread.Sleep(1) will let any threads of the same or lower priority execute.

在调度程序让另一个线程执行之前,每个线程都有一个执行时间间隔.正如 Billy ONeal 所说,调用 Thread.Sleep 将把这个时间间隔的剩余时间交给其他线程(取决于上面的优先级考虑).

Each thread is given an interval of time to execute in, before the scheduler lets another thread execute. As Billy ONeal states, calling Thread.Sleep will give up the rest of this interval to other threads (subject to the priority considerations above).

Windows 平衡整个操作系统的线程 - 不仅仅是在您的进程中.这意味着操作系统上的其他线程也可能导致您的线程被抢占(即中断并将剩余的时间间隔分配给另一个线程).

Windows balances over threads over the entire OS - not just in your process. This means that other threads on the OS can also cause your thread to be pre-empted (ie interrupted and the rest of the time interval given to another thread).

有一篇文章可能对 Thread.Sleep(x) 的主题感兴趣:

There is an article that might be of interest on the topic of Thread.Sleep(x) at:

优先级饥饿:为什么要睡觉(1) 优于 Sleep(0) 和 Windows 平衡集管理器

这篇关于有人可以用 Sleep(1) 解释这个有趣的行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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