Posted on 2007-11-29 18:17
dennis 閱讀(1178)
評論(0) 編輯 收藏 所屬分類:
linux & C
先是讀《Programming in Lua》第9章講
coroutine,然后去google coroutine,找到Simon Tatham寫的一篇coroutine in c,講怎么在C語言中實現(xiàn)coroutine,文中先ugly地基于棧實現(xiàn)了一個:
int function(void) {
static int i, state = 0;
switch (state) {
case 0: goto LABEL0;
case 1: goto LABEL1;
}
LABEL0: /* start of function */
for (i = 0; i < 10; i++) {
state = 1; /* so we will come back to LABEL1 */
return i;
LABEL1:; /* resume control straight after the return */
}
}
這個方法簡單,但是相當丑陋,你必須手工維護這些標簽。然后提到了Duff's Device技巧:
switch (count % 8) {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while ((count -= 8) > 0);
}
這段代碼能編譯通過嗎?能的,不信你試試,這是一段用于拷貝數(shù)組的代碼,我們一般拷貝數(shù)組是這樣做的:
send(to, from, count)
register short *to, *from;
register count;
{
do
*to = *from++;
while(--count>0);
}
如果循環(huán)的中的操作足夠快,那么其實大部分時間都是浪費在判斷循環(huán)條件上面的,而通過Duff's Device通過switch語句將要進行的連續(xù)循環(huán)操作的次數(shù)進行了預判(根據(jù)擦case語句的位置)然后依次執(zhí)行,而不必每次都去進 行測試條件,從而加速循環(huán)。這個技巧怎么應用于實現(xiàn)更優(yōu)雅的
coroutine呢?看代碼
int function(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 */
}
}
}
更好的方式是使用宏:
#define crBegin static int state=0; switch(state) { case 0:
#define crReturn(i,x) do { state=i; return x; case i:; } while (0)
#define crFinish }
int function(void) {
static int i;
crBegin;
for (i = 0; i < 10; i++)
crReturn(1, i);
crFinish;
}