C++ 库 - <coroutine>



C++20 中的<coroutine> 库提供了使用协程的基本构建块。协程是允许函数在某些点暂停和恢复的现代特性。它提供了一种有效的异步编程、生成器函数和协作多任务处理机制,从而更容易处理网络、文件 I/O 等任务。

与传统函数不同,协程可以在某些点暂停其执行并在以后恢复。这在需要有效实现非阻塞操作(如文件 I/O 或网络请求)的场景中特别有用。

包含 <coroutine> 头文件

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

#include <coroutine>

<coroutine> 头文件的功能

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

序号 函数和描述
1 operator=

它赋值 coroutine_handle 对象。

2 operator coroutine_handle<>

它获取一个类型擦除的 coroutine_handle。

3 done

它检查协程是否已完成。

4 operator bool

它检查句柄是否代表一个协程。

5 operator() & resume

它恢复协程的执行。

6 destroy

它销毁一个协程。

7 promise

它访问协程的 promise。

8 address

它导出底层地址。

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

生成序列

在下面的示例中,我们将创建一个生成整数序列的协程。

#include <iostream> #include <coroutine> struct x { struct promise_type { int a; int b = 0; x get_return_object() { return x { this }; } std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() {} std::suspend_always yield_value(int val) { a = val; return {}; } int getNext() { return b++; } }; promise_type * promise; x(promise_type * p): promise(p) {} int next() { promise -> yield_value(promise -> getNext()); return promise -> a; } }; x generateSequence() { for (int i = 0; i < 4; ++i) { co_yield i; } } int main() { auto sequence = generateSequence(); for (int i = 0; i < 4; ++i) { std::cout << "Next value: " << sequence.next() << '\n'; } return 0; }

输出

以下是上述代码的输出:

Next value: 0
Next value: 1
Next value: 2
Next value: 3
广告