什么是 std::promise?

我对 C++11 的 std::threadstd::asyncstd::future 组件相当熟悉(例如,请参阅此答案),这些很简单.

I'm fairly familiar with C++11's std::thread, std::async and std::future components (e.g. see this answer), which are straight-forward.

然而,我无法完全理解 std::promise 是什么,它的作用是什么,在什么情况下最适合使用.标准文档本身不包含除类概要之外的大量信息,std::thread.

However, I cannot quite grasp what std::promise is, what it does and in which situations it is best used. The standard document itself doesn't contain a whole lot of information beyond its class synopsis, and neither does std::thread.

有人可以举一个简短的例子来说明需要 std::promise 的情况以及它是最惯用的解决方案吗?

Could someone please give a brief, succinct example of a situation where an std::promise is needed and where it is the most idiomatic solution?

推荐答案

用[futures.state]的话来说,std::future是一个异步返回对象(从共享状态读取结果的对象"),std::promise 是异步提供者(向共享状态提供结果的对象") 即承诺是您设置结果的东西,以便您可以从相关的未来获得它.

In the words of [futures.state] a std::future is an asynchronous return object ("an object that reads results from a shared state") and a std::promise is an asynchronous provider ("an object that provides a result to a shared state") i.e. a promise is the thing that you set a result on, so that you can get it from the associated future.

异步提供者最初创建未来引用的共享状态.std::promise 是一种异步提供者,std::packaged_task 是另一种,std::async 的内部细节是另一种.每个都可以创建一个共享状态,并为您提供一个共享该状态的 std::future,并且可以使该状态准备就绪.

The asynchronous provider is what initially creates the shared state that a future refers to. std::promise is one type of asynchronous provider, std::packaged_task is another, and the internal detail of std::async is another. Each of those can create a shared state and give you a std::future that shares that state, and can make the state ready.

std::async 是一个更高级别的便利实用程序,它为您提供异步结果对象,并在内部负责创建异步提供程序并在任务完成时准备共享状态.你可以用一个 std::packaged_task(或 std::bind 和一个 std::promise)和一个 std 来模拟它::thread 但使用 std::async 更安全、更容易.

std::async is a higher-level convenience utility that gives you an asynchronous result object and internally takes care of creating the asynchronous provider and making the shared state ready when the task completes. You could emulate it with a std::packaged_task (or std::bind and a std::promise) and a std::thread but it's safer and easier to use std::async.

std::promise 有点低级,用于当你想将异步结果传递给未来,但使结果就绪的代码不能包含在单个函数中适合传递给 std::async.例如,您可能有一个由多个 promise 和关联的 future 组成的数组,并且有一个线程来执行多个计算并为每个 promise 设置一个结果.async 只允许你返回一个结果,返回多个你需要多次调用 async ,这可能会浪费资源.

std::promise is a bit lower-level, for when you want to pass an asynchronous result to the future, but the code that makes the result ready cannot be wrapped up in a single function suitable for passing to std::async. For example, you might have an array of several promises and associated futures and have a single thread which does several calculations and sets a result on each promise. async would only allow you to return a single result, to return several you would need to call async several times, which might waste resources.

相关文章