std::promise provides a means of setting a value (of type T), which can later be read through an associated std::future object
这两者究竟有何关联?
我担心 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);
}
}
}
}
最佳答案
将
promise
和future
视为创建一次性数据通道。promise
创建 channel ,并最终使用promise::set_value
将数据写入其中。future
连接到 channel ,future::wait
读取并返回写入后的数据。不用担心,因为将
future
与promise
“配对”的唯一方法是使用promise::get_future
.
关于c++ - C++ 中的 std::promise 和 std::future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25878765/