基于windows fiber的协程(coroutine)实现
一个非常简单,但是实用的协程实现,使用Windows的*Fiber
函数族(linux可以稍微改一下用*context
函数族)。
fco.h
#ifndef _MSC_VER
#error "this fast coroutine library only supports MSVC building chain"
#endif
#include <Windows.h>
#include <cstdint>
#include <map>
namespace fco {
static constexpr int ERR_NOT_EXIST_CO = -1;
enum Status {
READY, // Set up to READY when fco::newco() called
AWAIT, // Set up to AWAIT when fco::yield() called
};
struct Scheduler;
struct Coroutine;
struct Coroutine {
void (*task)(Scheduler*, void*);
void* userData;
char status;
LPVOID winFiber;
};
struct Scheduler {
std::map<int, Coroutine*> coroutines;
int currentIdx;
LPVOID main;
};
void __stdcall __entry(LPVOID lpParameter);
Scheduler* initialize();
void destroy(Scheduler* s);
int newco(Scheduler* scheduler, void (*task)(Scheduler*, void*),
void* userData);
void resume(Scheduler* s, int coid);
void yield(Scheduler* scheduler);
int current(Scheduler* scheduler);
} // namespace fco
fco.cpp
#include "fco.h"
// Initialize fco library, return a global scheduler
fco::Scheduler* fco::initialize() {
Scheduler* sched = new Scheduler;
sched->currentIdx = ERR_NOT_EXIST_CO;
sched->main = ConvertThreadToFiber(NULL);
return sched;
}
// Release all resources
void fco::destroy(Scheduler* s) {
for (auto& c : s->coroutines) {
DeleteFiber(c.second->winFiber);
}
delete s;
}
// This is should NEVER BE called on user land
void __stdcall fco::__entry(LPVOID lpParameter) {
// Execute the task of current coroutine
Scheduler* s = (Scheduler*)lpParameter;
Coroutine* currentCo = s->coroutines[s->currentIdx];
(currentCo->task)(s, currentCo->userData);
// Clean up executed task
s->coroutines.erase(s->coroutines.find(s->currentIdx));
s->currentIdx = ERR_NOT_EXIST_CO;
currentCo->status = Status::READY;
DeleteFiber(currentCo->winFiber);
delete currentCo;
// Switch to entry function
SwitchToFiber(s->main);
}
// Create new coroutine and return an unique identity
int fco::newco(Scheduler* scheduler, void (*task)(fco::Scheduler*, void*),
void* userData) {
Coroutine* co = new Coroutine;
co->task = task;
co->userData = userData;
co->winFiber = CreateFiber(0, __entry, scheduler);
if (co->winFiber == NULL) {
return ERR_NOT_EXIST_CO;
}
co->status = Status::READY;
int newCoId =
scheduler->coroutines.size() != 0
? scheduler->coroutines.end().operator--().operator*().first + 1
: 0;
scheduler->coroutines.insert(std::make_pair(newCoId, co));
return newCoId;
}
// Resume suspended coroutine by given coid
void fco::resume(fco::Scheduler* scheduler, int coid) {
if (coid < 0) {
return;
}
Coroutine* co = scheduler->coroutines[coid];
if (co->status == Status::READY || co->status == Status::AWAIT) {
scheduler->currentIdx = coid;
scheduler->coroutines[scheduler->currentIdx]->status = Status::AWAIT;
co->status = Status::READY;
SwitchToFiber(co->winFiber);
}
}
// Yield CPU time to main coroutine
void fco::yield(fco::Scheduler* scheduler) {
Coroutine* co = scheduler->coroutines[scheduler->currentIdx];
co->status = Status::AWAIT;
scheduler->currentIdx = ERR_NOT_EXIST_CO;
SwitchToFiber(scheduler->main);
}
// Get current running coroutine identity
int fco::current(Scheduler* scheduler) { return scheduler->currentIdx; }
example
- hello world
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
#include "fco.h"
void bar(fco::Scheduler* s, void* param) {
for (int i = 0; i < 5; i++) {
std::cout << "world\n";
fco::yield(s);
}
}
int main() {
fco::Scheduler* s = fco::initialize();
int barFunc = fco::newco(s, bar, nullptr);
for (int i = 0; i < 5; i++) {
std::cout << "hello\n";
fco::resume(s, barFunc);
}
fco::destroy(s);
return 0;
}
- 生产者消费者模型
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>
#include "fco.h"
std::vector<int> vec;
void producer(fco::Scheduler* s, void* param) {
while (vec.size() < 10) {
int resource = rand();
std::cout << "Producing " << resource << "\n";
vec.push_back(resource);
}
fco::resume(s, (int)param);
fco::yield(s);
}
void consumer(fco::Scheduler* s, void* param) {
int producerCo = fco::newco(s, producer, (void*)fco::current(s));
while (true) {
while (!vec.empty()) {
int resource = vec.back();
vec.pop_back();
std::cout << "Consuming " << resource << "\n";
}
fco::resume(s, producerCo);
}
}
void factory() {
fco::Scheduler* s = fco::initialize();
int consumerCo = fco::newco(s, consumer, nullptr);
fco::resume(s, consumerCo);
fco::destroy(s);
}
int main() {
srand((int)time(0));
factory();
system("pause");
return 0;
}
基于windows fiber的协程(coroutine)实现的更多相关文章
- 协程coroutine
协程(coroutine)顾名思义就是“协作的例程”(co-operative routines).跟具有操作系统概念的线程不一样,协程是在用户空间利用程序语言的语法语义就能实现逻辑上类似多任务的编程 ...
- qemu核心机制分析-协程coroutine
关于协程coroutine前面的文章已经介绍过了,本文总结对qemu中coroutine机制的分析,qemu 协程coroutine基于:setcontext函数族以及函数间跳转函数siglongjm ...
- Python并发编程协程(Coroutine)之Gevent
Gevent官网文档地址:http://www.gevent.org/contents.html 基本概念 我们通常所说的协程Coroutine其实是corporate routine的缩写,直接翻译 ...
- 并发编程协程(Coroutine)之Gevent
并发编程协程之Gevent Gevent官网文档地址:http://www.gevent.org/contents.html 基本概念 我们通常所说的协程Coroutine其实是corporate r ...
- Unity协程(Coroutine)管理类——TaskManager工具分享
博客分类: Unity3D插件学习,工具分享 源码分析 Unity协程(Coroutine)管理类——TaskManager工具分享 By D.S.Qiu 尊重他人的劳动,支持原创,转载请注明出处 ...
- (zt)Lua的多任务机制——协程(coroutine)
原帖:http://blog.csdn.net/soloist/article/details/329381 并发是现实世界的本质特征,而聪明的计算机科学家用来模拟并发的技术手段便是多任务机制.大致上 ...
- Lua的多任务机制——协程(coroutine)
并发是现实世界的本质特征,而聪明的计算机科学家用来模拟并发的技术手段便是多任务机制.大致上有这么两种多任务技术,一种是抢占式多任务(preemptive multitasking),它让操作系统来决定 ...
- Unity协程Coroutine使用总结和一些坑
原文摘自 Unity协程Coroutine使用总结和一些坑 MonoBehavior关于协程提供了下面几个接口: 可以使用函数或者函数名字符串来启动一个协程,同时可以用函数,函数名字符串,和Corou ...
- 【Unity】协程Coroutine及Yield常见用法
最近学习协程Coroutine,参考了别人的文章和视频教程,感觉协程用法还是相当灵活巧妙的,在此简单总结,方便自己以后回顾.Yield关键字的语意可以理解为“暂停”. 首先是yield return的 ...
随机推荐
- OceanBase
OceanBase 编辑 本词条缺少名片图,补充相关内容使词条更完整,还能快速升级,赶紧来编辑吧! OceanBase是一个支持海量数据的高性能分布式数据库系统,实现了 数千亿条记录.数百TB数据上的 ...
- Ubuntu16.0安装Eclipse Neon
eclipse在Ubuntu下安装先安装jdk,配置环境变量,之后下载eclipse安装包,解压,放置在目标目录,将jre链接到该目录或者将jdk下的jre目录复制到eclipse安装包目录下,双击文 ...
- Excel数据透视表
Excel中每列是一个字段,每行是一条记录. 值字段设置,双击更改统计方法. 双击透视表中的数据可以看具体是哪些记录贡献的这些数据. 显示报表筛选页,生成多个工作簿.
- [随笔]CENTOS7更换YUM源为163源(记录一下以防忘记)
2016年2月16日,最新163源变更后的更新方法: 访问地址为:http://mirrors.163.com/.help/centos.html 首先备份源: mv /etc/yum.repos.d ...
- ETC系统简介
ETC:电子不停车系统 主要由两部分构成:OBU(车载单元,又叫电子标签)和RSU(路基单元,包括天线) 其中OBU里插有用户卡(一般是和银行联名发行的信用卡) 而RSU包括路基天线,PSAM卡,通过 ...
- mysql中查看表结构的sql语句
mysql查看表结构命令,如下: desc 表名;show columns from 表名;describe 表名;show create table 表名; use information_sche ...
- [operator]ELK6的安装
找了很久才找到一个博客写得比较全面的,FrankDeng 系统环境:CentOS7 相关软件:node-v10.9.0.tar.gz.kibana-6.4.0-linux-x86_64.tar.gz. ...
- eclipse Multiple annotations found at this line
参考:http://blog.csdn.net/li396864285/article/details/42745071 这样的错不影响编程,是eclipse的校验问题 去掉相应的Build就行了
- CodeForces 540B School Marks (贪心)
题意:先给定5个数,n, k, p, x, y.分别表示 一共有 n 个成绩,并且已经给定了 k 个,每门成绩 大于0 小于等于p,成绩总和小于等于x, 但中位数大于等于y.让你找出另外的n-k个成 ...
- 利用predis操作redis方法大全
predis是PHP连接Redis的操作库,由于它完全使用php编写,大量使用命名空间以及闭包等功能,只支持php5.3以上版本,故实测性能一般,每秒25000次读写. 将session数据存放到re ...