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程序来具体化这个概念:
#include <iostream> using namespace std; int switch_magic(void) { static int i, state = 0; switch (state) { case 0: /* start of function */ for (i = 0; i < 10; i++) { state = 1; /* so we will come back to "case 1" */ return i; case 1:; /* resume control straight after the return */ } } return -1; } int main() { cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; return 0; }
运行输出:
0
1
2
3
4
5
6
7
8
9
-1
通过定义一些精巧的macro可以屏蔽coroutine的C实现细节,让代码更加简单、易读:
#include <iostream> using namespace std; #define crBegin static int state=0; switch(state) { case 0: #define crReturn(x) do { state=__LINE__; return x; \ case __LINE__:; } while (0) #define crFinish } int switch_magic(void) { static int i; crBegin for (i = 0; i < 10; i++) crReturn(i); crFinish return -1; } int main() { cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; cout << switch_magic() << endl; return 0; }
参考资料:
原文链接: https://www.cnblogs.com/edwardlost/archive/2010/11/02/1861742.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/16905
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!