Created
July 26, 2026 02:28
-
-
Save CarterLi/7d1baa10d7719743282e3dab7dbcd0e4 to your computer and use it in GitHub Desktop.
HighRes_WaitForSingleObject
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @brief 高精度等待单个对象 | |
| * @param hTarget 目标对象 (如 Event, Semaphore) | |
| * @param hHRTimer 预先创建的高分辨率 Waitable Timer (用于复用,避免频繁创建 Handle) | |
| * @param timeout_ms 超时时间 (毫秒) | |
| * @return WAIT_OBJECT_0 (目标触发) 或 WAIT_TIMEOUT (超时) | |
| */ | |
| DWORD HighRes_WaitForSingleObject(HANDLE hTarget, HANDLE hHRTimer, DWORD timeout_ms) { | |
| // 1. 设置高分辨率 Timer (负值表示相对时间,单位 100ns) | |
| // 调用 SetWaitableTimer 会自动取消之前的倒计时,并将 Timer 置为 Non-Signaled 状态 | |
| LARGE_INTEGER dueTime; | |
| dueTime.QuadPart = -((LONGLONG)timeout_ms * 10000); | |
| if (!SetWaitableTimer(hHRTimer, &dueTime, 0, NULL, NULL, FALSE)) { | |
| return WAIT_FAILED; | |
| } | |
| // 2. 构建等待数组: [0]=目标对象, [1]=高精度 Timer | |
| HANDLE handles[2] = { hTarget, hHRTimer }; | |
| // 3. 调用 NtWaitForMultipleObjects | |
| // 关键: Timeout 参数传 NULL (即 INFINITE) | |
| // 因为超时逻辑已经完全由 hHRTimer 接管,我们不需要内核再做一层粗粒度的超时判断 | |
| NTSTATUS status = NtWaitForMultipleObjects( | |
| 2, // 等待 2 个对象 | |
| handles, | |
| WaitAny, // 任意一个触发即唤醒 | |
| FALSE, // 不可警报 | |
| NULL // 原生 Timeout 设为 INFINITE | |
| ); | |
| // 4. 解析竞争结果 | |
| if (status == STATUS_WAIT_0) { | |
| // 索引 0 (hTarget) 先触发 | |
| return WAIT_OBJECT_0; | |
| } | |
| else if (status == STATUS_WAIT_0 + 1) { | |
| // 索引 1 (hHRTimer) 先触发 -> 意味着超时 | |
| return WAIT_TIMEOUT; | |
| } | |
| else { | |
| // 其他错误或被 APC 中断 | |
| return WAIT_FAILED; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment