【问题标题】:Why does GetExitCodeThread() return FALSE here?为什么 GetExitCodeThread() 在这里返回 FALSE?
【发布时间】:2019-09-20 04:20:15
【问题描述】:

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

【问题讨论】:

    标签: c++ multithreading winapi mfc


    【解决方案1】:

    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 将由于类型不兼容而导致编译器错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-19
      • 2016-06-30
      • 2020-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多