C++20 无栈协程实现生产者消费者模型

该文展示了如何在C++中使用协程处理异步操作,定义了一个`coro_ret`模板结构体来管理协程的生命周期,并通过`promise_type`进行协程内外的数据交换。示例中创建了一个生产者协程`producer`,它按顺序生成数字并挂起,然后在`main`函数中消费这些数字。
#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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值