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

Pen*_*nny 1 c++ winapi mfc multithreading

我有一个小的测试代码。我的假设在下面的代码中,因为我没有设置标志来停止线程,所以在的行中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;
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 5

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

CWinThread具有operator HANDLE()获取正确的线程Win32句柄的方法,例如:

CWinThread *pThread = AfxBeginThread(...);
if (!pThread) ... // error handling
hOriginalThread = *pThread;
Run Code Online (Sandbox Code Playgroud)

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