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

See this video tutorial on C++11 futures.

Explicitly with threads and futures:

#include <thread>
#include <future>

void func(std::promise<int> && p) {
    p.set_value(1);
}

std::promise<int> p;
auto f = p.get_future();
std::thread t(&func, std::move(p));
t.join();
int i = f.get();

Or with std::async (higher-level wrapper for threads and futures):

#include <thread>
#include <future>
int func() { return 1; }
std::future<int> ret = std::async(&func);
int i = ret.get();

I can't comment whether it works on all platforms (it seems to work on Linux, but doesn't build for me on Mac OSX with GCC 4.6.1).


I'd say:

#include <thread>
#include <future>

int simplefunc(std::string a)
{ 
    return a.size();
}

int main()
{
      auto future = std::async(simplefunc, "hello world");
      int simple = future.get();

      return simple;
}

Note that async even propagates any exceptions thrown from the thread function


Using C++11 threads, one can't get the return value as thread exit which used to be the case with pthread_exit(...)

You need to use C++11 Future<> to get the return value. Future is created using templated argument where the template takes the return value (built in of User Defined types)..

You can fetch the value in another thread using future<..>::get(..) function.

one benefit of using future<..> is that you can check the validity of return value i.e if it's already taken, you avoid calling get() accidentally by checking the validity using future<..>::isValid(...) function.

Here is how you'll write the code.

#include <iostream>
#include <future>
using namespace std;
auto retFn() {
    return 100;
}
int main() {
    future<int> fp = async(launch::async, retFn);
    if(fp.valid())
       cout<<"Return value from async thread is => "<<fp.get()<<endl;
    return 0;
}

it should also be noted that we can get the future run on the same thread by using launch::deferred option as

 future<int> fp = async(launch::deferred, retFn);