stdex.coroutine C++11 非对称协程库开源项目

我要开发同款
匿名用户2016年10月01日
82阅读

技术信息

开源地址
https://github.com/tonbit/coroutine
授权协议
Apache

作品详情

C++11非对称协程库(只需要单独一个.h文件)

支持几个必备的协程原语(命名空间coroutie):

创建协程:routie_t create(std::fuctio<void()> f);

销毁协程:void destroy(routie_t id);

恢复协程执行:it resume(routie_t id);

放弃协程执行:void yield();

等待异步任务结果:TYPE await(TYPE(*f)());

获取当前协程的ID:routie_tcurret();

SPSC通信模板类:classChael<T>:支持push()/pop()操作;

 

#iclude <iostream>#iclude <chroo>//只需下载iclude此文件#iclude "coroutie.h"//SPSC通道,多个生产者或消费者,协程调度行为不好控制coroutie::Chael<it> chael; strig asyc_fuc(){    std::this_thread::sleep_for(std::chroo::millisecods(3000));    retur "21";}void routie_fuc1(){    //从通道中获取消息,如果没有消息会yield    it i = chael.pop();    std::cout << i << std::edl;    i = chael.pop();    std::cout << i << std::edl;}void routie_fuc2(it i){    std::cout << "20" << std::edl;    //放弃当前协程的执行,返回恢复点    coroutie::yield();    std::cout << "21" << std::edl;        //异步执行任务,如果任务无法立即执行完毕,会yield    strig str = coroutie::await(asyc_fuc);    std::cout << str << std::edl;}void thread_fuc(){    //创建协称,回调函数形式为:std::fuctio<void()>    coroutie::routie_t rt1 = coroutie::create(routie_fuc1);    coroutie::routie_t rt2 = coroutie::create(std::bid(routie_fuc2, 2));        std::cout << "00" << std::edl;    //恢复rt1    coroutie::resume(rt1);    std::cout << "01" << std::edl;    //恢复rt2    coroutie::resume(rt2);    std::cout << "02" << std::edl;    //向通道推送消息    chael.push(10);    std::cout << "03" << std::edl;    coroutie::resume(rt2);    std::cout << "04" << std::edl;    chael.push(11);    std::cout << "05" << std::edl;    //销毁协程。    //建议:协程在执行完毕后统一释放,这样协程栈空间中的对象能够安全的被到释放。    coroutie::destroy(rt1);    coroutie::destroy(rt2);}it mai(){    std::thread t1(thread_fuc);    std::thread t2([](){        //不支持跨线程的协程调度    });    t1.joi();    t2.joi();    retur 0;}

功能介绍

C++11 非对称协程库(只需要单独一个.h文件) 支持几个必备的协程原语(命名空间coroutine): 创建协程:routine_t create( std::function<void()...

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论