劉強(qiáng)東自己做網(wǎng)站圖片優(yōu)化網(wǎng)站
一:什么是協(xié)程(Coroutines):
協(xié)程是輕量級(jí)線程,可以暫停和恢復(fù)執(zhí)行,協(xié)程擁有自己的暫停點(diǎn)狀態(tài),協(xié)程暫停時(shí),將當(dāng)前狀態(tài)保存起來,在恢復(fù)執(zhí)行時(shí)會(huì)恢復(fù)之前保存的狀態(tài)。
二:例子:
#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) //創(chuàng)建生成器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