一:什么是協程(Coroutines):
協程是輕量級線程,可以暫停和恢復執行,協程擁有自己的暫停點狀態,協程暫停時,將當前狀態保存起來,在恢復執行時會恢復之前保存的狀態。
二:例子:
#include <coroutine>
#include <iostream>void doTheWork() {std::cout << "Processing shared data." << std::endl;
}
template<typename T>
struct Generator {struct promise_type;using handle_type = std::coroutine_handle<promise_type>;Generator(handle_type h) : coro(h) {} // (3) //創建生成器handle_type coro;~Generator() {if (coro) coro.destroy();}Generator(const Generator&) = delete;Generator& operator = (const Generator&) = delete;Generator(Generator&& oth) noexcept : coro(oth.coro) {oth.coro = nullptr;}Generator& operator = (Generator&& oth) noexcept {coro = oth.coro;oth.coro = nullptr;return *this;}T getValue() {re