std :: promise <t>线程安全吗?

时间:2017-03-01 14:30:45

标签: c++ c++11 asynchronous promise

是否安全,例如std::mutex std::promise<T> mutableT,还是依赖于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()); } ?如:

for(i in 5:12)
{
  for(j in 5:12)
  {
    for(k in 5:12)
    {
      for(l in 5:12)
      {
        cat(i,j,k,l,'\n')
      }
    }
  }
}

1 个答案:

答案 0 :(得分:4)

让我们详细了解一下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,因此我们无法从中推断出有关常量的任何知识。但是,该标准规定了以下方法的线程安全性(c.f。33.6.6.2):set_­valueset_­exceptionset_­value_­at_­thread_­exitset_­exception_­at_­thread_­exit

这使得get_future未指定线程安全性。但是,如果多次调用,get_future会抛出异常,c.f。 33.6.6.14.1。因此,从实际的角度来看,从多个线程调用get_future并没有多大意义。

在调用get_future和任何set方法和get_future(无论是否会抛出)时,无法保证线程安全,就我而言可以看到。

相关问题