【发布时间】: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