当我使用 WaitForSingleObject 函数等待无信号事件时,我发现在某些情况下,调用将在小于指定的超时期限内返回 WAIT_TIMEOUT。只需在超时设置为 1000 毫秒的情况下循环调用,我就看到调用在低至 990 毫秒的时间内返回(在 WinXP 上运行)。我正在使用QueryPerformanceCounter来获得独立于系统时钟的时间测量,因此我认为时钟漂移不太可能是答案。
这种行为不会给我带来任何实际问题,但我想更好地理解它。看起来它可能以大约计时器滴答的分辨率工作。 Microsoft 是否发布了有关此函数精度的更多详细信息?我应该期待 Vista 中更高的精度吗?
最佳答案
是的,WaitForSingleObject 使用计时器刻度分辨率,它不使用像 QueryPerformanceCounter 这样的高分辨率计时器。
http://msdn.microsoft.com/en-us/library/ms687069(VS.85).aspx ,关于“等待函数”的 MSDN 文章对此进行了扩展:
The accuracy of the specified time-out interval depends on the resolution of the system clock. The system clock "ticks" at a constant rate. If the time-out interval is less than the resolution of the system clock, the wait may time out in less than the specified length of time. If the time-out interval is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on.
本文还解释了如何使用 timeBeginPeriod 来提高系统时钟分辨率 - 但不建议这样做。
我可以想到几个原因。首先,几乎所有 WaitForSingleObject 用例都不需要更高的分辨率。使用高分辨率定时器需要内核不断轮询定时器(不可行,因为不能保证内核代码始终运行)或频繁重新编程以生成中断(因为可能有多个 WaitForSingleObjects,并且很可能只有一个)可编程中断)。
另一方面,已经有一个可以不断更新的计时源,其分辨率足以满足 WaitForSingleObject、SetWaitableTimer 和 Sleep 的要求。
关于winapi - WaitForSingleObject超时解决,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/895242/