Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you get the return value of a Windows thread?

I was just wondering if it is possible (and if so, how) to get the return value of a thread in C++ (Windows). I have several threads, and I use WaitForMultipleObjects(...) on them. This waits until a thread is done, and returns the index of said thread, and all is well. However, I want to be able to obtain the return value of the thread that finished using its handle.

For example:

DWORD WINAPI Thread1(void *parameter){
    ...
    if(...) return 0;
    else return -1;
}

DWORD WINAPI Thread2(void *parameter){
    ...
    if(...) return 1;
    else return 0;
}

int main(){
    HANDLE t1 = CreateThread(0, 0, Thread1, NULL, 0, 0);
    HANDLE t2 = CreateThread(0, 0, Thread2, NULL, 0, 0);
    HANDLE *threads = new HANDLE[2];
    threads[0] = t1;
    threads[1] = t2;
    int result = WaitForMultipleObjects(2, threads, false, INFINITE);
    if(result == 0){
        //get the threads value here:
        int retVal = SomeFunction(t1); //What is SomeFunction?
    }
    ...
}

I have tried to use GetExitCodeThread(thread) but I'm assuming this returns a system exit code, as it always gives me a very strange integer. Does anyone know a way, or a workaround?

like image 511
Sefu Avatar asked Aug 17 '11 22:08

Sefu


1 Answers

GetExitCodeThread is the correct function. Here is the MSDN description of what it does:

This function returns immediately. If the specified thread has not terminated and the function succeeds, the status returned is STILL_ACTIVE. If the thread has terminated and the function succeeds, the status returned is one of the following values:

  • The exit value specified in the ExitThread or TerminateThread function.
  • The return value from the thread function.
  • The exit value of the thread's process.
like image 118
Don Reba Avatar answered Nov 01 '22 08:11

Don Reba