为什么在调用GetThreadTimes时会出现错误“句柄无效”?

时间:2013-10-11 21:19:25

标签: c++ windows multithreading visual-c++ mfc

我需要获取工作线程的CPU时间。我似乎必须使用GetThreadTimes来执行此操作,因为我的目标是Windows XP及更新版本。根据文档,Windows XP不支持QueryThreadCycleTime

以下是我写的测试程序的内容:

#include <windows.h>

UINT TestFunction(LPVOID pParam)
{
    TRACE("Thread Started!\n");
    Sleep(10000);
    TRACE("Thread about to terminate!\n");
    return 0;
}

...

CWinThread* thread = AfxBeginThread(TestFunction, NULL);

Sleep(500);

LPFILETIME creationTime = NULL;
LPFILETIME exitTime = NULL;
LPFILETIME kernelTime = NULL;
LPFILETIME userTime = NULL;

int result = GetThreadTimes(thread, creationTime, exitTime, kernelTime, userTime);

TRACE("Result: %d\n", result);

if(result != 0)
{
    TRACE("Got result!\n");
}
else
{
    //ref: http://msdn.microsoft.com/en-us/library/windows/desktop/ms680582(v=vs.85).aspx
    LPVOID lpMsgBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL
    );

    TRACE("Timing query failed with error %d: %s", dw, lpMsgBuf);

    LocalFree(lpMsgBuf);

...

我得到以下调试输出:

Thread Started!
Result: 0
Timing query failed with error 6: The handle is invalid.

这是为什么?我们知道线程正在运行,因为“Thread Started!”跟踪消息。我已经尝试调整睡眠时间,直到线程终止。我仍然得到无效的句柄错误。

测试程序是使用Visual C ++ 6构建的MFC应用程序。

1 个答案:

答案 0 :(得分:2)

您的threadCWinThread *。您传递给GetThreadTimes的参数应为HANDLE

CWinThread有一个强制转换操作符来获取该线程的操作系统句柄,因此您应该可以使用:GetThreadTimes(*thread, ...)

还有另一个问题:你真的需要改变这些:

LPFILETIME creationTime = NULL;
LPFILETIME exitTime = NULL;
LPFILETIME kernelTime = NULL;
LPFILETIME userTime = NULL;

对于这样的事情:

FILETIME creationTime;
FILETIME exitTime;
FILETIME kernelTime;
FILETIME userTime;

然后,当您调用该函数时,您传递了每个函数的地址,因此您的调用如下所示:

GetThreadTimes(*thread, &creationTime, &exitTime, &kernelTime, &userTime);