std::future
is used only in multithreaded programs. Such programs use threads, which can be thought of as mutually independent subprograms, to perform some tasks. For a 6-years child, this would be like when several people do something independently to achieve some task, e.g. mommy buys tickets while daddy books a hotel. Now, these "threads", "workers", "subprograms" need to communicate to share / transfer some data securely. The problem is that since they are completely independent, one needs a mechanism with which the "producer" of the information can either send it to the "consumer" or communicate its failure to produce the data; similarly, the "consumer" or "receiver" must have a secure, reliable way to tell whether a) the data from another thread is ready b) receive the data and c) receive the error signal should the "producer" fail to produce the data.
One method of providing such synchronization mechanism is a promise-future pair. They always go in pairs - if you can see std::future
without std::promise
, it's because the latter has been hidden from you, but it's somewhere. std::promise
is used by the producer to set (and "send") the data, whereas std::future
is used by "consumer" to receive it. If the producer cannot fulfil the contract, that is, if it cannot produce or "satisfy" the promise with the data, it may satisfy it with an exception, which is a C++ method of telling that something has gone wrong. Then, the "consumer" will receive this exception instead of data via its std::future
.
In summary:
std::future
is an object used in multithreaded programming to receive data or an exception from a different thread; it is one end of a single-use, one-way communication channel between two threads, std::promise
object being the other end. Using the promise-future pattern, you have a guarantee that your inter-thread communication is free of common errors specific to multithreaded programs, like race conditions or accessing already freed memory, which are very common if the threads "talk to each other" using methods designed for single-threaded programs, like when function (=thread) arguments are being passed by reference.