Coroutine介绍

boost::asio实例中的HTTP Server 4使用“stackless coroutines”实现,还从来没见过这种诡异又极其难读的代码,遂到网上八了一下,原来coroutines是一个古老的计算模式,中文翻译叫“协程”,在现代程序语言里面属于“非主流”,erlang语言就是采用的这种模式。

 

coroutine和subroutine的不同点在于coroutine可以很多个调用入口点,而subroutine只能有一个。当coroutine被第一次调用到的时候,它将从起始处开始执行,一旦遇到具有yield(类似subroutine中的return语句)语义的语句的时候,就是返回给另外一个coroutine或者调用者,而在接下来再次被调用的时候,就从yield语句下面的一条语句继续执行直到遇到新的yield语句或者coroutine的结束。

 

对于subroutine调用方式已根深蒂固的开发者说,上面的coroutine介绍肯定是非常抽象和空洞的,下面就通一个使用C++实现的一个coroutine程序来具体化这个概念:

01#include <iostream>
02 
03using namespace std;
04 
05int switch_magic(void) {
06    static int i, state = 0;
07    switch (state) {
08        case 0: /* start of function */
09        for (i = 0; i < 10; i++) {
10            state = 1; /* so we will come back to "case 1" */
11            return i;
12            case 1:; /* resume control straight after the return */
13        }
14    }
15     
16    return -1;
17}
18 
19int main() {
20    cout << switch_magic() << endl;
21    cout << switch_magic() << endl;
22    cout << switch_magic() << endl;
23    cout << switch_magic() << endl;
24    cout << switch_magic() << endl;
25    cout << switch_magic() << endl;
26    cout << switch_magic() << endl;
27    cout << switch_magic() << endl;
28    cout << switch_magic() << endl;
29    cout << switch_magic() << endl;
30    cout << switch_magic() << endl;
31    return 0;
32}

运行输出:

0
1
2
3
4
5
6
7
8
9
-1


通过定义一些精巧的macro可以屏蔽coroutine的C实现细节,让代码更加简单、易读:

01#include <iostream>
02 
03using namespace std;
04 
05#define crBegin static int state=0; switch(state) { case 0:
06 
07#define crReturn(x) do { state=__LINE__; return x; \
08                         case __LINE__:; } while (0)
09 
10#define crFinish }
11 
12int switch_magic(void) {
13    static int i;
14    crBegin
15    for (i = 0; i < 10; i++)
16        crReturn(i);
17    crFinish
18 
19    return -1;
20}
21 
22int main() {
23    cout << switch_magic() << endl;
24    cout << switch_magic() << endl;
25    cout << switch_magic() << endl;
26    cout << switch_magic() << endl;
27    cout << switch_magic() << endl;
28    cout << switch_magic() << endl;
29    cout << switch_magic() << endl;
30    cout << switch_magic() << endl;
31    cout << switch_magic() << endl;
32    cout << switch_magic() << endl;
33    cout << switch_magic() << endl;
34    return 0;
35}

 

参考资料:

说说一个新的老概念coroutine 

Coroutine - Wiki

Coroutines in C

Coroutine实现有感


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值