c++ - C++ 中的 std::promise 和 std::future

标签 c++ multithreading

std::promise provides a means of setting a value (of type T), which can later be read through an associated std::future object

  1. 这两者究竟有何关联?

  2. 我担心 future 会与错误的 promise 配对是否合理?

更新:来自并发操作的示例...(虽然代码无法编译)

#include <future>
void process_connections(connection_set& connections)
{
    while(!done(connections)){
        for(connection_iterator
        connection=connections.begin(),end=connections.end();
        connection!=end;
        ++connection)
        {
            if(connection->has_incoming_data()){
                data_packet data=connection->incoming();
                std::promise<payload_type>& p=
                connection->get_promise(data.id);
                p.set_value(data.payload);
            }
            if(connection->has_outgoing_data()){
                outgoing_packet data=
                connection->top_of_outgoing_queue();
                connection->send(data.payload);
                data.promise.set_value(true);
            }
        }
    }
}

最佳答案

  1. promisefuture 视为创建一次性数据通道。 promise 创建 channel ,并最终使用 promise::set_value 将数据写入其中。 future 连接到 channel ,future::wait 读取并返回写入后的数据。

  2. 不用担心,因为将 futurepromise “配对”的唯一方法是使用 promise::get_future .

关于c++ - C++ 中的 std::promise 和 std::future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878765/

相关文章:

c++ - 在多线程环境中将局部变量作为常量引用传递

c++ - 使用时 0xcdcdcdcd->

c++ - 类型转换与 memcpy() : which one is better?

c++ - 无法找到 Valgrind 检测到的内存泄漏

java - 是否值得清理 Filter 中的 ThreadLocals 来解决与线程池相关的问题?

c++ - 按钮按下处理 win32 c++

c++ - MSB 到 LSB 交换后保留符号和小数

C++模板非类型参数lambda函数

java - 使用 Executor 和 WebSocket 的多线程

.net - System.Threading.Monitor.Enter()如何工作?