Getting return value from a boost::threaded member function?

He Shiming picture He Shiming · Nov 11, 2009 · Viewed 11.8k times · Source

I have a worker class like the one below:

class Worker{
public:
  int Do(){
    int ret = 100;
    // do stuff
    return ret;
  }
}

It's intended to be executed with boost::thread and boost::bind, like:

Worker worker;
boost::function<int()> th_func = boost::bind(&Worker::Do, &worker);
boost::thread th(th_func);
th.join();

My question is, how do I get the return value of Worker::Do?

Thanks in advance.

Answer

tgoodhart picture tgoodhart · Nov 14, 2011

Another option is to use promises/futures.

class Worker{
public:
  void Do( boost::promise<int> & p){
    int ret = 100;
    // do stuff
    p.set_value(ret);
  }
};
//Later...
boost::promise<int> p;
boost::thread t( boost::bind(&Worker::Do, &worker, boost::ref(p));
int retval = p.get_future().get(); //This will block until the promise is set.

And if you can use c++0x, then using std::async will package up all of the above and just do:

std::future<int> f = std::async( std::bind(&Worker::Do, &worker) );
int retval = f.get(); //Will block until do returns an int.