为什么 GetExitCodeThread() 在这里返回 FALSE?
Why does GetExitCodeThread() return FALSE here?
我有一个小的测试代码。我的假设在下面的代码中,因为我没有设置标志来停止线程,然后在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
将导致编译器错误,因为类型不兼容。
相关文章:
- QueryWorkingSet总是返回false
- 当返回类型声明为 ListNode 时,我们是否可以返回 false<T>*
- 等于在 c++ 中返回 false
- strcmp 对于相等的字符序列返回 false
- C++ - 负数和正数之间的比较返回 false
- protobuf 的 ParseFromString 函数返回 false
- 递归函数始终返回 false
- 为什么 GetExitCodeThread() 在这里返回 FALSE?
- MFC 的 OnInit() 函数中的返回 true 和返回 false 有什么区别
- if 语句在条件为真时返回 false
- 为什么 std::isnan() 对于具有 NAN 值的双变量返回 false
- is_lock_free() 在升级到 MacPorts gcc 7.3 后返回 false
- 在 winapi 回调函数上返回 FALSE 时出现意外行为(循环被跳过?
- 如果数组中有重复的数字,如何返回'false'?
- std::is_array 当它应该返回 false 时返回 true
- 为什么pyarg_parsetuple总是返回false
- 删除为应该在哈希表中的记录返回 false 的函数
- Vulkan 和 glfwVulkanSupported() 总是返回 false
- tf2_ros::Buffer::canTransform() 为现有转换返回 False
- 出于某种原因,布尔值返回 false