【问题标题】:Exit code of thread in Windows C++Windows C++中线程的退出代码
【发布时间】:2011-05-24 19:13:00
【问题描述】:
假设我创建了多个线程。
现在我也在等待多个对象:
WaitOnMultipleObject(...);
现在如果我想知道所有线程的返回码的状态。该怎么做?
我是否需要在循环中循环所有线程的句柄。
GetExitCodeThread(
__in HANDLE hThread,
__out LPDWORD lpExitCode
);
现在检查lpExitCode 的成功/失败代码?
干杯,
悉达多
【问题讨论】:
标签:
c++
windows
multithreading
exit
【解决方案1】:
如果您想等待线程退出,只需等待线程的句柄即可。等待完成后,您可以获得该线程的退出代码。
DWORD result = WaitForSingleObject( hThread, INFINITE);
if (result == WAIT_OBJECT_0) {
// the thread handle is signaled - the thread has terminated
DWORD exitcode;
BOOL rc = GetExitCodeThread( hThread, &exitcode);
if (!rc) {
// handle error from GetExitCodeThread()...
}
}
else {
// the thread handle is not signaled - the thread is still alive
}
通过将线程句柄数组传递给WaitForMultipleObjects(),可以将此示例扩展为等待多个线程完成。在从WaitForMultipleObjects() 返回时,找出使用从WAIT_OBJECT_0 的适当偏移量完成的线程,并在调用它以等待下一个线程完成时从传递给WaitForMultipleObjects() 的句柄数组中删除该线程句柄。
【解决方案2】:
我是否需要循环所有线程的
循环处理。
GetExitCodeThread(
__in HANDLE hThread,
__out LPDWORD lpExitCode
);
是的。