Jam*_*mes 5 c++ asynchronous promise c++11
它是安全的,就像在的情况下,std::mutex对std::promise<T>被提出mutable,或者它取决于T?如:
using Data = std::tuple<bool, int, int>;
struct X {
    std::future<Data> prepare() const {
        return m_promise.get_future();
    }
    void asyncHandler(int a, int b) const {
        m_promise.set_value({true, a, b});
    }
    void cancel() const {
        m_promise.set_value({false, 0, 0});
    }
    mutable std::promise<Data> m_promise;  // Is this safe?
};
void performAsyncOp(const X& x) {
     std::future<Data> fut = x.prepare();
     dispatch(x);
     std::future_status result = fut.wait_for(std::chrono::milliseconds(150));
     if (result == std::future_status::timeout) {
         x.cancel();
     }
     handleResult(fut.get());
}
让我们详细看一下API:
// retrieving the result
future<R> get_future();
// setting the result
void set_value(see below);
void set_exception(exception_ptr p);
// setting the result with deferred notification
void set_value_at_thread_exit(see below);
void set_exception_at_thread_exit(exception_ptr p);
没有一个方法被标记const,所以我们不能仅仅从这个推断任何关于常量的知识。但是,下面的方法标准的任务线程安全的(参见33.6.6.2)set_value,set_exception,set_value_at_thread_exit,和set_exception_at_thread_exit。
这get_future在线程安全方面未指定。但是,get_future如果多次调用会引发异常,参见33.6.6.14.1。所以get_future从实际的角度来看,从多个线程调用并没有真正的意义。
据我所知,在调用get_future和任何set方法和get_future(无论它是否会抛出)时,都不能保证线程安全。
| 归档时间: | 
 | 
| 查看次数: | 914 次 | 
| 最近记录: |