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.
You can take a look at the "boost::future" concept, ref this link
Another option is using the Boost.Lambda library. Then you can write the code as follows without changing the
Worker
class:This is useful in particular when you cannot change the function to call. Like this, the return value is wrapped in a local variable
ret
.In addition, you also have some redundant calls to boost::bind() and boost::function(). You can instead do the following:
You can do this because Thread's constructor is a convenience wrapper around an internal bind() call. Thread Constructor with arguments
Another option is to use promises/futures.
And if you can use c++0x, then using std::async will package up all of the above and just do:
I don't think you can get the return value.
Instead, you can store the value as a member of Worker:
And use it like so: