为什么 GetExitCodeThread() 在这里返回 FALSE?

Why does GetExitCodeThread() return FALSE here?

本文关键字:返回 FALSE 在这里 GetExitCodeThread 为什么      更新时间:2023-10-16

我有一个小的测试代码。我的假设在下面的代码中,因为我没有设置标志来停止线程,然后在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--ThreadFuncn");
printf("Thread loop start: --ThreadFunc");
while (!bExit)
{
iCount++;
if (iCount % 50 == 0)
printf(".");
}
printf("Thread loop end: %d--ThreadFuncn", iCount++);
printf("end thread--ThreadFuncn");
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--Mainn", GetLastError());
}
while (bStatus && dwEC == STILL_ACTIVE)
{
printf("Check Thread in active: %d--Mainn", iTry);
Sleep(1);
iTry++;
if (iTry>5)
{
printf("Try to terminate Thread loop: %d--Mainn", iTry++);
TerminateThread(hOriginalThread, 0);// Force thread exit
}
bStatus = GetExitCodeThread(hOriginalThread, &dwEC);
}
hThread = NULL;
printf("End Main --Mainn");
return 0;
}

AfxBeginThread()返回一个CWinThread*对象指针,而不是像CreateThread()那样返回Win32HANDLE。因此,GetExitCodeThread()由于线程句柄无效而失败,GetLastError()应该告诉您。

CWinThread有一个operator HANDLE()来获取线程的正确 Win32 句柄,例如:

CWinThread *pThread = AfxBeginThread(...);
if (!pThread) ... // error handling
hOriginalThread = *pThread;

你的代码甚至编译的原因是因为你很可能没有在启用STRICT类型检查的情况下进行编译,所以HANDLE只是一个简单的void*,任何类型的指针都可以分配给它。如果启用 STRICT,则不会void*HANDLE,并且将AfxBeginThread()的返回值直接分配给hOriginalThread将导致编译器错误,因为类型不兼容。