升压等同的std ::异步的() [英] Boost equivalent of std::async()
问题描述
如果不使用的boost ::线程
和的boost ::绑定
直接,有没有实现等价的方式以下code的?
Without using boost::thread
and boost::bind
directly, is there a way to implement the equivalent of the following code?
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;
}
具体而言,这一部分:<?code>自动FTR =的std ::异步(安培; FUNC);
推荐答案
当然可以。只是让异步&LT; T&GT;(STD ::功能&LT; T()&GT;)
返回一个未来它调用 FUNC()
目前它的第一个等待换。你不会得到任何异步性,但是API实际上不保证该函数将异步运行,所以这不是一个问题。
Certainly. Simply make async<T>(std::function<T()>)
return a future which invokes func()
the moment it's first waited-for. You won't get any asynchronicity, but the API doesn't actually guarantee that the function will run asynchronously, so that's not a problem.
如果您有机会获得一个特定的操作系统线程库,你当然可以使用为好。
If you have access to an OS-specific threading library, you could of course use that as well.
请注意,但是,存储异常不能可移植性执行;它需要从C ++实现额外的支持,除非你可以限制支持那些具有多态克隆功能的异常。见<一href=\"http://stackoverflow.com/questions/2960554/correct-way-to-store-an-exception-in-a-variable\">this问题了解详情。
Note, however, that storing exceptions cannot be implemented portably; it requires additional support from the C++ implementation, unless you can restrict the exceptions supported to ones with a polymorphic clone function. See this question for more information.
最后的实现可能看起来有点像这样(未经):
The final implementation might look a bit like this (untested):
// 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();
}
};
这篇关于升压等同的std ::异步的()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!