std::promise provides a means of setting a value (of type T), which can later be read through an associated std::future object
How exactly these two are associated?
Is my concern reasonable that the future would pair with the wrong promise?
update: example from concurrency in action... (the code cannot compile, though)
#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);
}
}
}
}
std::future A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads. "Valid" futures are future objects associated to a shared state, and are constructed by calling one of the following functions: async.
The class template std::promise provides a facility to store a value or an exception that is later acquired asynchronously via a std::future object created by the std::promise object. Note that the std::promise object is meant to be used only once.
3) std::future is not CopyConstructible.
How to create a future ? The simplest way is to use std::async that will create an asynchronous task and return a std::future . Nothing really special here. std::async will execute the task that we give it (here a lambda) and return a std::future .
Think of promise
and future
as creating a single-use channel for data. promise
creates the channel, and eventually writes the data to it with promise::set_value
. future
connects to the channel, and future::wait
reads and returns the data once it's been written.
No real concern, because the only way to "pair" a future
with a promise
is with promise::get_future
.
They are associated by the std::promise::get_future
member function. You get the std::future
associated with an std::promise
by calling this function.
A std::future
represents a value that you do not yet have, but will have eventually. It provides functionality to check whether the value is available yet, or to wait for it to be available.
A std::promise
makes a promise that you will eventually set a value. When a value is eventually set, it will be made available through its corresponding std::future
.
No, because you don't pair them after creation. You get your std::future
from a std::promise
, so they are inherently linked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With