首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在超时中处理GetTickCount()溢出

在超时中处理GetTickCount()溢出
EN

Code Review用户
提问于 2016-05-20 17:52:39
回答 1查看 1.8K关注 0票数 3

这是必须在XP上运行的代码,所以没有GetTickCount64,并且在49天后应该正确地处理值的包装。还能改进吗?

代码语言:javascript
复制
// DWORD timeoutMs is a given parameter.

DWORD beginMs = (timeoutMs == INFINITE ? 0 : ::GetTickCount());
DWORD endMs = beginMs + timeoutMs; // unsigned arithmethic is Mod(MAX+1)
DWORD currentMs;

// Create Process, omitted for brevity

while ((waitResult = ::WaitForSingleObject(pi.hProcess, DEFAULT_WAIT_MS)) == WAIT_TIMEOUT)
{
    if (timeoutMs != INFINITE)
    {
        bool timeoutReached = false;
        currentMs = ::GetTickCount();
        if (beginMs <= endMs) // normal case
        {
            if (currentMs > endMs)
            {
                timeoutReached = true;
            }
        }
        else // special case: tick count wrapped around after 49 days uptime
        {
            if (currentMs < beginMs && currentMs > endMs)
            {
                timeoutReached = true;
            }
        }

        if (timeoutReached)
        {
            ::TerminateProcess(pi.hProcess, 0);
            break;
        }
    }
}
EN

回答 1

Code Review用户

回答已采纳

发布于 2016-05-30 11:02:31

无符号减法(和自动mod 2^32)总是给出currentMs - beginMs == elapsedMs,即使是beginMs > currentMs,只要实际运行的时间不溢出滴答计数(它不大于49天)。

因此,您可以用以下代码替换原始代码:

代码语言:javascript
复制
DWORD beginMs = GetTickCount();

// Create Process, omitted for brevity

while ((waitResult = WaitForSingleObject(pi.hProcess, DEFAULT_WAIT_MS)) == WAIT_TIMEOUT) {
    if (timeoutMs != INFINITE) {
        DWORD currentMs = GetTickCount();
        bool timeoutReached = currentMs - beginMs > timeoutMs;
        if (timeoutReached) {
            TerminateProcess(pi.hProcess, 0);
            break;
        }
    }
}

您甚至可以更进一步,消除变量currentMstimeoutReachedif (GetTickCount() - beginMs > timeoutMs) {...

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/128879

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档