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

I'm just wondering if (and if so, how) it is possible to get the return value of a stream in C ++ (Windows). I have multiple threads and I use WaitForMultipleObjects(...) for them. This waits until the thread is executed, and returns the index of the specified thread, and everything will be fine. However, I want to be able to get the return value of a thread that has finished using its handle.

For instance:

 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 tried using GetExitCodeThread(thread) , but I assume this returns the system exit code, as it always gives me a very weird integer. Does anyone know a way or workaround?

+6
source share
4 answers

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

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

  • The output value specified in the ExitThread or TerminateThread function.
  • The return value from the stream function.
  • The output value of the stream process.
+11
source

The problem with most programmers is that they do not pay attention to compiler warnings. At level 4 (/ W4), the compiler generates the following warning when returning -1 from a function that returns a DWORD :

warning C4245: 'return' : conversion from 'int' to 'DWORD', signed/unsigned mismatch

+3
source

you need to check STILL_ACTIVE for values ​​that one of these threads can be active

+1
source

You can use C ++ 11 thread concepts with std::future .
See the example below.

 int ReturnFrmThread() { return 100; } int main() { std::future<int> GetRetVal= std::async(ReturnFrmThread); // Execution of ReturnFrmThread starts int answer = GetAnAnswer.get(); // gets value as 100; // Waits until ReturnFrmThread has finished } 
0
source

Source: https://habr.com/ru/post/895288/


All Articles