从 boost::threaded 成员函数获取返回值?
我有一个如下所示的工作类:
class Worker{
public:
int Do(){
int ret = 100;
// do stuff
return ret;
}
}
它旨在使用 boost::thread 和 boost::bind 执行,例如:
Worker worker;
boost::function<int()> th_func = boost::bind(&Worker::Do, &worker);
boost::thread th(th_func);
th.join();
我的问题是,如何获取 Worker::Do 的返回值?
提前致谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
另一种选择是使用承诺/期货。
如果您可以使用 c++0x,那么使用 std::async 将打包以上所有内容,然后执行以下操作:
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:
我认为你无法获得返回值。
相反,您可以将该值存储为 Worker 的成员:
并像这样使用它:
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:
此外,您还对 boost::bind() 和 boost::function() 进行了一些冗余调用。您可以执行以下操作:
您可以执行此操作,因为 Thread 的构造函数是内部 bind() 调用的便捷包装器。 带参数的线程构造函数
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
你可以看一下“boost::future”的概念,参考这个链接
You can take a look at the "boost::future" concept, ref this link
另一种选择是使用 Boost.Lambda 库。然后,您可以编写如下代码,而无需更改
Worker
类:这在您无法更改要调用的函数时尤其有用。像这样,返回值被包装在局部变量
ret
中。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
.