std::shared_future::wait

From cppreference.com

 
 
Thread support library
Threads
(C++11)
this_thread namespace
(C++11)
(C++11)
(C++11)
(C++11)
Mutual exclusion
(C++11)
(C++11)
(C++17)
Generic lock management
(C++11)
(C++11)
(C++14)
(C++11)
(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
Condition variables
(C++11)
Futures
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
(C++11)
 
 
void wait() const;
(since C++11)

Blocks until the result becomes available. valid() == true after the call.

The behavior is undefined if valid()== false before the call to this function.

Contents

[edit] Parameters

(none)

[edit] Return value

(none)

[edit] Exceptions

(none)

[edit] Notes

The implementations are encouraged to detect the case when valid == false before the call and throw a std::future_error with an error condition of std::future_errc::no_state.

Calling wait on the same std::shared_future from multiple threads is not safe; the intended use is for each thread that waits on the same shared state to have a copy of a std::shared_future.

[edit] Example

#include <iostream>
#include <future>
#include <thread>
 
int fib(int n)
{
  if (n < 3) return 1;
  else return fib(n-1) + fib(n-2);
}
 
int main()
{
    std::shared_future<int> f1 = std::async(std::launch::async, [](){
        return fib(20);
    });
    std::shared_future<int> f2 = std::async(std::launch::async, [](){
        return fib(25);
    });
 
    std::cout << "waiting...\n";
    f1.wait();
    f2.wait();
 
    std::cout << "f1: " << f1.get() << '\n';
    std::cout << "f2: " << f2.get() << '\n';
}

Output:

waiting...
f1: 6765
f2: 75025

[edit] See also

waits for the result, returns if it is not available for the specified timeout duration
(public member function)
waits for the result, returns if it is not available until specified time point has been reached
(public member function)