Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/thread/future"

From cppreference.com
< cpp‎ | thread
m (Member functions)
(Undo revision 170131 by Lynnboy (talk))
 
(10 intermediate revisions by 7 users not shown)
Line 2: Line 2:
 
{{cpp/thread/future/navbar}}
 
{{cpp/thread/future/navbar}}
 
{{dcl begin}}
 
{{dcl begin}}
{{dcl header | future}}
+
{{dcl header|future}}
{{dcl | num=1 | since=c++11 |
+
{{dcl|num=1|since=c++11|
 
template< class T > class future;
 
template< class T > class future;
 
}}
 
}}
{{dcl | num=2 | since=c++11 |
+
{{dcl|num=2|since=c++11|
 
template< class T > class future<T&>;
 
template< class T > class future<T&>;
 
}}
 
}}
{{dcl | num=3 | since=c++11 |
+
{{dcl|num=3|since=c++11|
template<>         class future<void>;
+
template<> class future<void>;
 
}}
 
}}
 
{{dcl end}}
 
{{dcl end}}
Line 18: Line 18:
 
* An asynchronous operation (created via {{lc|std::async}}, {{lc|std::packaged_task}}, or {{lc|std::promise}}) can provide a {{tt|std::future}} object to the creator of that asynchronous operation.
 
* An asynchronous operation (created via {{lc|std::async}}, {{lc|std::packaged_task}}, or {{lc|std::promise}}) can provide a {{tt|std::future}} object to the creator of that asynchronous operation.
  
* The creator of the asynchronous operation can then use a variety of methods to query, wait for, or extract a value from the {{tt|std::future}}. These methods may block if the asynchronous operation has not yet provided a value.
+
* The creator of the asynchronous operation can then use a variety of methods to query, wait for, or extract a value from the {{tt|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. {{lc|std::promise::set_value}}) that is linked to the creator's {{tt|std::future}}.
+
* When the asynchronous operation is ready to send a result to the creator, it can do so by modifying ''shared state'' (e.g. {{lc|std::promise::set_value}}) that is linked to the creator's {{tt|std::future}}.
  
 
Note that {{tt|std::future}} references shared state that is not shared with any other asynchronous return objects (as opposed to {{lc|std::shared_future}}).  
 
Note that {{tt|std::future}} references shared state that is not shared with any other asynchronous return objects (as opposed to {{lc|std::shared_future}}).  
Line 26: Line 26:
 
===Member functions===
 
===Member functions===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/thread/future/dsc constructor | future}}
+
{{dsc inc|cpp/thread/future/dsc constructor|future}}
{{dsc inc | cpp/thread/future/dsc destructor}}
+
{{dsc inc|cpp/thread/future/dsc destructor}}
{{dsc inc | cpp/thread/future/dsc operator{{=}}}}
+
{{dsc inc|cpp/thread/future/dsc operator{{=}}}}
{{dsc inc | cpp/thread/future/dsc share}}
+
{{dsc inc|cpp/thread/future/dsc share}}
  
{{dsc h2 | Getting the result}}
+
{{dsc h2|Getting the result}}
{{dsc inc | cpp/thread/future/dsc get | future}}
+
{{dsc inc|cpp/thread/future/dsc get|future}}
  
{{dsc h2 | State}}
+
{{dsc h2|State}}
{{dsc inc | cpp/thread/future/dsc valid | future}}
+
{{dsc inc|cpp/thread/future/dsc valid|future}}
{{dsc inc | cpp/thread/future/dsc wait | future}}
+
{{dsc inc|cpp/thread/future/dsc wait|future}}
{{dsc inc | cpp/thread/future/dsc wait_for | future}}
+
{{dsc inc|cpp/thread/future/dsc wait_for|future}}
{{dsc inc | cpp/thread/future/dsc wait_until | future}}
+
{{dsc inc|cpp/thread/future/dsc wait_until|future}}
 
{{dsc end}}
 
{{dsc end}}
  
===Example===
+
===Examples===
 
{{example
 
{{example
| code=
+
|code=
#include <iostream>
+
 
#include <future>
 
#include <future>
 +
#include <iostream>
 
#include <thread>
 
#include <thread>
  
Line 51: Line 51:
 
{
 
{
 
     // future from a packaged_task
 
     // future from a packaged_task
     std::packaged_task<int()> task([](){ return 7; }); // wrap the function
+
     std::packaged_task<int()> task([]{ return 7; }); // wrap the function
     std::future<int> f1 = task.get_future(); // get a future
+
     std::future<int> f1 = task.get_future(); // get a future
     std::thread(std::move(task)).detach(); // launch on a thread
+
     std::thread t(std::move(task)); // launch on a thread
  
 
     // future from an async()
 
     // future from an async()
     std::future<int> f2 = std::async(std::launch::async, [](){ return 8; });
+
     std::future<int> f2 = std::async(std::launch::async, []{ return 8; });
  
 
     // future from a promise
 
     // future from a promise
 
     std::promise<int> p;
 
     std::promise<int> p;
 
     std::future<int> f3 = p.get_future();
 
     std::future<int> f3 = p.get_future();
     std::thread( [](std::promise<int> p){ p.set_value_at_thread_exit(9); },
+
     std::thread([&p]{ p.set_value_at_thread_exit(9); }).detach();
                std::move(p) ).detach();
+
  
 
     std::cout << "Waiting..." << std::flush;
 
     std::cout << "Waiting..." << std::flush;
Line 70: Line 69:
 
     std::cout << "Done!\nResults are: "
 
     std::cout << "Done!\nResults are: "
 
               << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
 
               << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
 +
    t.join();
 
}
 
}
| output=
+
|output=
 
Waiting...Done!
 
Waiting...Done!
 
Results are: 7 8 9
 
Results are: 7 8 9
 +
}}
 +
 +
====Example with exceptions====
 +
{{example
 +
|code=
 +
#include <future>
 +
#include <iostream>
 +
#include <thread>
 +
 +
int main()
 +
{
 +
    std::promise<int> p;
 +
    std::future<int> f = p.get_future();
 +
 +
    std::thread t([&p]
 +
    {
 +
        try
 +
        {
 +
            // code that may throw
 +
            throw std::runtime_error("Example");
 +
        }
 +
        catch (...)
 +
        {
 +
            try
 +
            {
 +
                // store anything thrown in the promise
 +
                p.set_exception(std::current_exception());
 +
            }
 +
            catch (...) {} // set_exception() may throw too
 +
        }
 +
    });
 +
 +
    try
 +
    {
 +
        std::cout << f.get();
 +
    }
 +
    catch (const std::exception& e)
 +
    {
 +
        std::cout << "Exception from the thread: " << e.what() << '\n';
 +
    }
 +
    t.join();
 +
}
 +
|output=
 +
Exception from the thread: Example
 
}}
 
}}
  
 
===See also===
 
===See also===
 
{{dsc begin}}
 
{{dsc begin}}
{{dsc inc | cpp/thread/dsc async}}
+
{{dsc inc|cpp/thread/dsc async}}
{{dsc inc | cpp/thread/dsc shared_future}}
+
{{dsc inc|cpp/thread/dsc shared_future}}
 
{{dsc end}}
 
{{dsc end}}
  
[[de:cpp/thread/future]]
+
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}
[[es:cpp/thread/future]]
+
[[fr:cpp/thread/future]]
+
[[it:cpp/thread/future]]
+
[[ja:cpp/thread/future]]
+
[[pt:cpp/thread/future]]
+
[[ru:cpp/thread/future]]
+
[[zh:cpp/thread/future]]
+

Latest revision as of 05:11, 12 March 2024

 
 
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
(C++11)
Generic lock management
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
future
(C++11)
(C++11)
(C++11)
Safe Reclamation
(C++26)
Hazard Pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11)(deprecated in C++20)
(C++11)(deprecated in C++20)
Memory ordering
Free functions for atomic operations
Free functions for atomic flags
 
 
Defined in header <future>
template< class T > class future;
(1) (since C++11)
template< class T > class future<T&>;
(2) (since C++11)
template<> class future<void>;
(3) (since C++11)

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

[edit] Member functions

constructs the future object
(public member function) [edit]
destructs the future object
(public member function) [edit]
moves the future object
(public member function) [edit]
transfers the shared state from *this to a shared_future and returns it
(public member function) [edit]
Getting the result
returns the result
(public member function) [edit]
State
checks if the future has a shared state
(public member function) [edit]
waits for the result to become available
(public member function) [edit]
waits for the result, returns if it is not available for the specified timeout duration
(public member function) [edit]
waits for the result, returns if it is not available until specified time point has been reached
(public member function) [edit]

[edit] Examples

#include <future>
#include <iostream>
#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 t(std::move(task)); // 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([&p]{ p.set_value_at_thread_exit(9); }).detach();
 
    std::cout << "Waiting..." << std::flush;
    f1.wait();
    f2.wait();
    f3.wait();
    std::cout << "Done!\nResults are: "
              << f1.get() << ' ' << f2.get() << ' ' << f3.get() << '\n';
    t.join();
}

Output:

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

[edit] Example with exceptions

#include <future>
#include <iostream>
#include <thread>
 
int main()
{
    std::promise<int> p;
    std::future<int> f = p.get_future();
 
    std::thread t([&p]
    {
        try
        {
            // code that may throw
            throw std::runtime_error("Example");
        }
        catch (...)
        {
            try
            {
                // store anything thrown in the promise
                p.set_exception(std::current_exception());
            }
            catch (...) {} // set_exception() may throw too
        }
    });
 
    try
    {
        std::cout << f.get();
    }
    catch (const std::exception& e)
    {
        std::cout << "Exception from the thread: " << e.what() << '\n';
    }
    t.join();
}

Output:

Exception from the thread: Example

[edit] See also

(C++11)
runs a function asynchronously (potentially in a new thread) and returns a std::future that will hold the result
(function template) [edit]
waits for a value (possibly referenced by other futures) that is set asynchronously
(class template) [edit]