Windows C++中线程的退出代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6115614/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:55:45  来源:igfitidea点击:

Exit code of thread in Windows C++

c++windowsmultithreadingexit

提问by siddhusingh

Suppose I have created multiple threads. Now I am waiting for multiple object as well using :

假设我创建了多个线程。现在我正在等待多个对象以及使用:

WaitOnMultipleObject(...);

Now if I want to know the status of all the thread's return code. How to do that ?

现在,如果我想知道所有线程返回码的状态。怎么做 ?

Do I need to loop for all the thread's handle in the loop.

我是否需要为循环中的所有线程句柄循环。

 GetExitCodeThread(
  __in   HANDLE hThread,
  __out  LPDWORD lpExitCode
);

And now check lpExitCodefor success / failure code ?

现在检查lpExitCode成功/失败代码?

Cheers, Siddhartha

干杯,悉达多

回答by John Dibling

Do I need to loop for all the thread's handle in the loop.

 GetExitCodeThread(
  __in   HANDLE hThread,
  __out  LPDWORD lpExitCode
);

我是否需要为循环中的所有线程句柄循环。

 GetExitCodeThread(
  __in   HANDLE hThread,
  __out  LPDWORD lpExitCode
);

Yes.

是的。

回答by Michael Burr

If you want to wait for a thread to exit, just wait on the thread's handle. Once the wait completes you can get the exit code for that thread.

如果要等待线程退出,只需等待线程的句柄即可。等待完成后,您可以获得该线​​程的退出代码。

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
}

This example can be extended to waiting for completion of several thread by passing an array of thread handles to WaitForMultipleObjects(). Figure out which thread completed using the appropriate offset from WAIT_OBJECT_0on the return from WaitForMultipleObjects(), and remove that thread handle from the handle array passed to WaitForMultipleObjects()when calling it to wait for the next thread completion.

通过将线程句柄数组传递给 ,可以将此示例扩展为等待多个线程完成WaitForMultipleObjects()。找出使用从WAIT_OBJECT_0返回的适当偏移量完成的线程WaitForMultipleObjects(),并WaitForMultipleObjects()在调用它以等待下一个线程完成时从传递给的句柄数组中删除该线程句柄。