Namespaces
Variants
Views
Actions

std::future

From cppreference.com
< cpp‎ | thread
Revision as of 17:13, 11 February 2013 by 85.176.201.159 (Talk)

Template:ddcl list begin <tr class="t-dsc-header">

<td>
Defined in header <future>
</td>

<td></td> <td></td> <tr class="t-dcl-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
template< class T > class future;
</td>

<td > (1) </td> <td > (since C++11) </td> </tr> <tr class="t-dcl-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
template< class T > class future<T&>;
</td>

<td > (2) </td> <td > (since C++11) </td> </tr> <tr class="t-dcl-sep"><td></td><td></td><td></td></tr>

<tr class="t-dcl ">

<td >
template<>          class future<void>;
</td>

<td > (3) </td> <td > (since C++11) </td> </tr> Template:ddcl list end

The class template std::future provides a mechanism to access the result of asynchronous operations:

  • The creator of the asynchronous operation can then use a variety of methods to query, wait for, or extract a value from the std::future. These methods may block if the asynchronous operation has not yet provided a value.
  • When the asynchronous operation is ready to send a result to the creator, it can do so by modifying shared state (e.g. std::promise::set_value) that is linked to the creator's std::future.

Note that std::future references shared state that is not shared with any other asynchronous return objects (as opposed to std::shared_future).

Contents

Member functions

Template:cpp/thread/future/dcl list constructorTemplate:cpp/thread/future/dcl list destructorTemplate:cpp/thread/future/dcl list operator=Template:cpp/thread/future/dcl list shareTemplate:cpp/thread/future/dcl list getTemplate:cpp/thread/future/dcl list validTemplate:cpp/thread/future/dcl list waitTemplate:cpp/thread/future/dcl list wait forTemplate:cpp/thread/future/dcl list wait until
Getting the result
State

Example

#include <iostream>
#include <future>
#include <thread>
 
int main()
{
    // future from a packaged_task
    std::packaged_task<int()> task([](){ return 7; }); // wrap the function
    std::future<int> f1 = task.get_future();  // get a future
    std::thread(std::move(task)).detach(); // launch on a thread
 
    // future from an async()
    std::future<int> f2 = std::async(std::launch::async, [](){ return 8; });
 
    // future from a promise
    std::promise<int> p;
    std::future<int> f3 = p.get_future();
    std::thread( [](std::promise<int>& p){ p.set_value(9); }, 
                 std::ref(p) ).detach();
 
    std::cout << "Waiting..." << std::flush;
    f1.wait();
    f2.wait();
    f3.wait();
    std::cout << "Done!\nResults are: "
              << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
}

Output:

Waiting...Done!
Results are: 7 8 9

See also

Template:cpp/thread/dcl list asyncTemplate:cpp/thread/dcl list shared future