如果不直接使用 boost::thread
和 boost::bind
,有没有办法实现以下代码的等价物?
std::string func()
{
std::string str("Hello from async task!");
return str;
}
int main()
{
auto ftr = std::async(&func);
std::cout << "Hello from main!";
std::string str = ftr.get();
std::cout << str << std::endl;
return 0;
}
具体来说,这部分:auto ftr = std::async(&func);
?
最佳答案
当然。只需制作 async<T>(std::function<T()>)
返回调用 func()
的 future 第一次等待的那一刻。您不会获得任何异步性,但 API 实际上并不能保证该函数将异步运行,因此这不是问题。
如果您可以访问特定于操作系统的线程库,您当然也可以使用它。
但是请注意,存储异常无法移植;它需要 C++ 实现的额外支持,除非您可以将支持的异常限制为具有多态克隆函数的异常。参见 this question获取更多信息。
最终的实现可能看起来有点像这样(未经测试):
// NOTE - we assume a SINGLE THREADED environment
template<typename T>
class myfuture_detail {
mutable boost::variant<T, boost::function<T()> > val;
public:
myfuture_detail(const boost::function<T()> &f)
: val(f) { }
const T &get() const {
if (T *t = boost::get<T>(&val)) {
return *t;
} else {
boost::function<T()> f = *boost::get<boost::function<T> >(&val);
val = f();
T *t = boost::get<T>(&val);
assert(t);
return *t;
}
}
};
template<typename T>
class myfuture {
boost::shared_ptr<myfuture_detail<T> > ptr;
public:
myfuture(const boost::function<T()> &f)
: ptr(boost::make_shared<myfuture_detail<T> >(f))
{}
myfuture() { }
const T &get() const {
return ptr->get();
}
};
关于c++ - boost 等效于 std::async(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8876459/