Timeout resolution of WaitForSingleObject

后端 未结 1 1435
小蘑菇
小蘑菇 2021-02-07 23:49

When I wait on a non-signaled Event using the WaitForSingleObject function, I find that in some cases the call will return WAIT_TIMEOUT in less than the specifi

相关标签:
1条回答
  • 2021-02-08 00:11

    Yes, WaitForSingleObject uses the timer tick resolution, it does not use a high-resolution timer like QueryPerformanceCounter.

    http://msdn.microsoft.com/en-us/library/ms687069(VS.85).aspx, the MSDN article on "Wait Functions" expands on this:

    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.

    This article also explains how to use timeBeginPeriod to increase system clock resolution - but this is not recommended.

    I can think of several reasons why. First, a higher resolution is not needed for nearly all use cases of WaitForSingleObject. Using a high-resolution timer would require the kernel to constantly poll the timer (not feasible since kernel code is not guaranteed to be always running) or reprogram it frequently to generate an interrupt (since there could be multiple WaitForSingleObjects and most likely only a single programmable interrupt).

    On the other hand, there already is a timing source that is constantly updatable at a resolution that is more than good enough for WaitForSingleObject, SetWaitableTimer, and Sleep.

    0 讨论(0)
提交回复
热议问题