我有一个小测试代码。我的假设是在下面的代码中,因为我没有设置标志来停止线程,然后在 GetExitCodeThread()
行中。它应该返回 TRUE
并且返回代码是 STILL_ACTIVE
。
而在实际测试中,结果是:
每次 GetExitCodeThread()
的返回值都是 FALSE
,所以在 main()
中,while
循环从未进入。有人可以告诉我原因吗?我的代码有什么问题。谢谢。
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "afxwin.h"
bool bExit = false;
HANDLE hOriginalThread;
static UINT ThreadFunc(LPVOID pParam)
{
int iCount = 0;
printf("start thread--ThreadFunc\n");
printf("Thread loop start: --ThreadFunc");
while (!bExit)
{
iCount++;
if (iCount % 50 == 0)
printf(".");
}
printf("Thread loop end: %d--ThreadFunc\n", iCount++);
printf("end thread--ThreadFunc\n");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
hOriginalThread = AfxBeginThread(ThreadFunc, (LPVOID)0, THREAD_PRIORITY_NORMAL, 0, 0);
Sleep(500);
DWORD dwEC;
int iTry = 0;
BOOL bStatus;
bStatus = GetExitCodeThread(hOriginalThread, &dwEC);
if (!bStatus)
{
printf("error GetExitCodeThread: %d--Main\n", GetLastError());
}
while (bStatus && dwEC == STILL_ACTIVE)
{
printf("Check Thread in active: %d--Main\n", iTry);
Sleep(1);
iTry++;
if (iTry>5)
{
printf("Try to terminate Thread loop: %d--Main\n", iTry++);
TerminateThread(hOriginalThread, 0);// Force thread exit
}
bStatus = GetExitCodeThread(hOriginalThread, &dwEC);
}
hThread = NULL;
printf("End Main --Main\n");
return 0;
}
最佳答案
AfxBeginThread()
返回 CWinThread*
对象指针,不是像 CreateThread()
这样的 Win32 HANDLE
做。因此 GetExitCodeThread()
由于线程句柄无效而失败,GetLastError()
应该已经告诉您了。
CWinThread
有一个 operator HANDLE()
获取线程的正确 Win32 句柄,例如:
CWinThread *pThread = AfxBeginThread(...);
if (!pThread) ... // error handling
hOriginalThread = *pThread;
您的代码甚至可以编译的原因是您可能没有使用 STRICT Type Checking 进行编译已启用,所以 HANDLE
只是一个简单的 void*
,任何 类型的指针都可以分配给它。如果启用 STRICT,HANDLE
将不会是 void*
并将 AfxBeginThread()
的返回值直接分配给 hOriginalThread
将由于类型不兼容导致编译器错误。
关于c++ - 为什么 GetExitCodeThread() 在这里返回 FALSE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58021719/