Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get return code from std::thread? [duplicate]

Possible Duplicate:
C++: Simple return value from std::thread?

Is there anyway to get the return code from a std::thread? I have a function which returns a integer, and I want to be able to get the return code from the function when the thread is done executing.

like image 419
whoosy Avatar asked Sep 07 '12 14:09

whoosy


2 Answers

No, that's not what std::thread is for.

Instead, use async to get a future:

#include <future>

int myfun(double, char, bool);

auto f = std::async(myfun, arg1, arg2, arg3);  // f is a std::future<int>

// ...

int res = f.get();

You can use the wait_for member function of f (with zero timeout) to see if the result is ready.

like image 175
Kerrek SB Avatar answered Oct 05 '22 12:10

Kerrek SB


As others have suggested, the facilities in <future> can be used for this. However I object to the answer

No, you can't do this with std::thread

Here is one way to do what you want with std::thread. It is by no means the only way:

#include <thread>
#include <iostream>

int func(int x)
{
    return x+1;
}

int main()
{
    int i;
    std::thread t([&] {i = func(2);});
    t.join();
    std::cout << i << '\n';
}

This will portably output:

3
like image 37
Howard Hinnant Avatar answered Oct 05 '22 11:10

Howard Hinnant