提升等效于std :: async()

Pat*_*ard 10 c++ boost asynchronous c++11

如果不使用boost::threadboost::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;
}
Run Code Online (Sandbox Code Playgroud)

具体而言,这一部分:auto ftr = std::async(&func);

bdo*_*lan 9

当然.简单地让async<T>(std::function<T()>)返回一个调用func()它第一次等待的时刻的未来.你不会得到任何异步性,但API实际上并不保证函数将异步运行,所以这不是问题.

如果您可以访问特定于操作系统的线程库,那么您当然也可以使用它.

但请注意,存储异常不能轻松实现; 它需要C++实现的额外支持,除非您可以将支持的异常限制为具有多态克隆功能的异常.有关更多信息,请参阅此问题.

最终的实现可能看起来有点像这样(未经测试):

// 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();
    }
};
Run Code Online (Sandbox Code Playgroud)