std::future::wait(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

🌸 NAME 🌸

std::future::wait β€” the C++ Standard Library member function std::future::wait(3) that literally just waits. No cap, that's the whole name. πŸ’…

✨ Synopsis ✨

void wait() const;  (since C++11)

Blocks until the result becomes available. After the call, valid() == true. 🫢

⚠️ The behavior is undefined if valid() == false before the call to this function. So please, bestie, vibe-check your future first. valid() is not a suggestion. 😭

🧸 Parameters 🧸

(none)

πŸŽ€ Return value πŸŽ€

(none)

πŸ’€ Exceptions πŸ’€

May throw implementation-defined exceptions.

🧠 Notes 🧠

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. 🚨

πŸ“ Example πŸ“

       // Run this code

        #include <chrono>
        #include <future>
        #include <iostream>
        #include <thread>

        int fib(int n)
        {
            if (n < 3)
                return 1;
            else
                return fib(n - 1) + fib(n - 2);
        }

        int main()
        {
            std::future<int> f1 = std::async(std::launch::async, []() { return
       fib(40); });
            std::future<int> f2 = std::async(std::launch::async, []() { return
       fib(43); });

            std::cout << "waiting... " << std::flush;
            const auto start = std::chrono::system_clock::now();

            f1.wait();
            f2.wait();

            const auto diff = std::chrono::system_clock::now() - start;
            std::cout << std::chrono::duration<double>(diff).count() << "
       seconds\n";

            std::cout << "f1: " << f1.get() << '\n';
            std::cout << "f2: " << f2.get() << '\n';
        }

🌈 Possible output 🌈

        waiting... 1.61803 seconds
        f1: 102334155
        f2: 433494437

πŸ‘€ See also πŸ‘€

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

That's the whole page, bestie: source http://cppreference.com, version/date 2024.06.10, and the manual page energy is std::future::wait(3). πŸ’–βœ¨

πŸ“¦ where this page comes from