C++ 库 - <future>



C++ 中的<future> 头文件提供了一种处理异步操作的方法,允许任务并发运行并在稍后获取结果。此库是更广泛的并发库的一部分,它使多线程编程变得更容易。

它通常与 std::async 结合使用,std::async 异步运行函数,或与 std::promise 结合使用,std::promise 手动设置 future 对象的值。当值准备好后,可以使用 future 对象的 get() 函数访问它。下面列出了常用的 C++ <future> 复制函数及其描述。

包含 <future> 头文件

要在您的 C++ 程序中包含 <future> 头文件,可以使用以下语法。

#include <future>

<future> 头文件的函数

以下是 <future> 头文件中所有函数的列表。

序号 函数及描述
1 operator=

它分配共享状态。

2 get_future

它返回与结果关联的 future。

3 set_value

它将结果设置为特定值。

4 set_exception

它将结果设置为指示异常。

5 set_value_at_thread_exit

它将结果设置为特定值,同时仅在线程退出时传递通知。

6 swap

它交换两个对象。

7 valid

它检查共享状态是否有效。

8 operator()

它调用存储的任务。

9 wait

它等待结果可用。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

等待 Future 就绪

在以下示例中,我们将使用 wait() 阻塞主线程,直到异步操作完成。

Open Compiler
#include <iostream> #include <future> #include <thread> int a(int x, int y) { std::this_thread::sleep_for(std::chrono::seconds(2)); return x + y; } int main() { std::future < int > b = std::async (std::launch::async, a, 2, 1); b.wait(); std::cout << "Result : " << b.get() << std::endl; return 0; }

输出

以下是上述代码的输出 -

Result : 3
广告