是std :: promise< T>线程安全的?

编程入门 行业动态 更新时间:2024-10-24 14:26:41
本文介绍了是std :: promise< T>线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

它是否安全,例如 std :: promise< T> 变为可变,还是取决于 T ?如:

Is it safe, like in the case of std::mutex for a std::promise<T> to be made mutable, or does it depend on T? As in:

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:

Let's have a detailed look at the 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 ,因此我们不能仅凭此推断出任何关于常数的知识。但是,该标准规定了以下方法的线程安全性(cf 33.6.6.2 ): set_value , set_exception , set_value_at_thread_exit 和 set_exception_at_thread_exit 。

None of the methods is marked const, so we can't infer any knowledge about the constness from just this. However, the standard mandates thread-safety on the following methods (c.f. 33.6.6.2): set_­value, set_­exception, set_­value_­at_­thread_­exit, and set_­exception_­at_­thread_­exit.

这使 get_future 的线程未指定-安全。但是,如果c.f多次调用 get_future ,则会引发异常。 33.6.6.14.1 。因此,从实际的角度来看,从多个线程调用 get_future 并没有什么意义。

This leaves get_future unspecified with respect to thread-safety. However, get_future throws an exception if called more than once, c.f. 33.6.6.14.1. So calling get_future from multiple threads doesn't really make sense from a practical point of view.

没有调用 get_future 以及任何 set 方法和 get_future 时的线程安全性保证据我所知,同时code>(无论它是否会抛出)。

There is no guarantee for thread-safety when calling get_future and any of the set methods and get_future (no matter if it will throw or not) simultaneously, as far as I can see.

更多推荐

是std :: promise&lt; T&gt;线程安全的?

本文发布于:2023-11-12 04:32:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1580519.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   promise   std   amp   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!