siddhusingh
siddhusingh

Reputation: 1868

Exit code of thread in Windows C++

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 lpExitCode for success / failure code ?

Cheers, Siddhartha

Upvotes: 2

Views: 9388

Answers (2)

Michael Burr
Michael Burr

Reputation: 340346

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_0 on 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.

Upvotes: 3

John Dibling
John Dibling

Reputation: 101484

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

 GetExitCodeThread(
  __in   HANDLE hThread,
  __out  LPDWORD lpExitCode
);

Yes.

Upvotes: 3

Related Questions