#include <coroutine>
#include <iostream>
#include <stdexcept>
#include <thread>
#include <queue>
#include <Windows.h>
//!coro_ret 协程函数的返回值,内部定义promise_type,承诺对象
template <typename T>
struct coro_ret
{
struct promise_type;
using handle_type = std::coroutine_handle<promise_type>;
//! 协程句柄
handle_type coro_handle_;
//coro_ret
coro_ret(handle_type h)
: coro_handle_(h)
{
}
coro_ret(const coro_ret&) = delete;
coro_ret(coro_ret&& s)
: coro_handle_(s.coro_)
{
s.coro_handle_ = nullptr;
}
~coro_ret()
{
//!自行销毁
if (coro_handle_)
{
coro_handle_.destroy();
}
}
coro_ret& operator=(const coro_ret& s)
{
coro_handle_ = s.coro_handle_;
return *this;
};
coro_ret& operator=(coro_ret&& s)
{
coro_handle_ = s.coro_hand
C++20 无栈协程实现生产者消费者模型
该文展示了如何在C++中使用协程处理异步操作,定义了一个`coro_ret`模板结构体来管理协程的生命周期,并通过`promise_type`进行协程内外的数据交换。示例中创建了一个生产者协程`producer`,它按顺序生成数字并挂起,然后在`main`函数中消费这些数字。

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



