1
我需要獲取工作線程的CPU時間。看來我必須使用GetThreadTimes來做到這一點,因爲我的目標是Windows XP和更新。根據文檔,Windows XP不支持QueryThreadCycleTime。爲什麼在調用GetThreadTimes時會出現「句柄無效」錯誤?
這是一個測試程序,我寫的肉:
#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.
這是爲什麼?我們知道線程正在運行,因爲「線程啓動!」跟蹤消息。我已經嘗試調整睡眠時間,直到線程終止。我仍然得到無效的句柄錯誤。
測試程序是內置在Visual C MFC應用程序++ 6.
有點讓人心寒,編譯器甚至可以讓你傳遞'CWinThread *' –
@DavidHeffernan:如果內存服務,在VC++ 6中使用'typedef void * HANDLE;',所以你可以傳遞任何指針作爲句柄。 –