在C++中,协程可以使用C++20中引入的std::coroutine
库来实现。协程使用co_await
关键字来暂时挂起当前协程的执行,并等待另一个协程完成后再继续执行。以下是一个简单的使用协程的示例:
#include#include struct task { struct promise_type { task get_return_object() { return task{std::coroutine_handle ::from_promise(*this)}; } std::suspend_never initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void return_void() {} void unhandled_exception() { std::terminate(); } }; std::coroutine_handle coro; task(std::coroutine_handle h) : coro(h) {} ~task() { if (coro) coro.destroy(); } }; task foo() { std::cout << "Start" << std::endl; co_await std::suspend_always{}; std::cout << "End" << std::endl; } int main() { auto t = foo(); t.coro.resume(); }
在这个示例中,我们定义了一个简单的协程foo
,在其中使用了co_await
关键字来暂时挂起协程的执行。在main
函数中,我们实例化了一个task
对象t
,然后手动调用了t.coro.resume()
方法来启动协程的执行。当协程执行到co_await std::suspend_always{}
时,会暂时挂起协程的执行,直到调用resume()
方法继续执行。