看到了一个有意思的东西,原文来自Matthew Lee翻译的文章,英文原文Simon Tatham 的文章 Coroutines in C,里面的程序对我来说理解起来有点难度,于是自己写了个更简单的。
基本思想就是用 state
变量来保存函数调用的状态,这里借助 ANSI C 提供了一个名为 __LINE__
的特殊的宏,代表了当前代码所在的行数。
#define coBegin \
static int __state = 0; \
switch (__state) { \
case 0:
#define coYield(x) \
__state = __LINE__; \
return x; \
case __LINE__:
#define coEnd }
注意宏展开后 __LINE__
为 coYield
所在的行号,所以两个 __LINE__
虽然看起来差两行但其实是同一个值。
coYield
可以在 coBegin
和 coEnd
之间任意多次使用,但是不能把两个 coYield
放在同一行里。
给出一个简单的 python 程序
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b # 使用 yield
a, b = b, a + b
n = n + 1
for n in fib(5):
print n
用上面的宏翻译成 C 就是
int fib() {
static int n = 0, a = 0, b = 1;
coBegin;
for (; n < 10; n++) {
coYield(b);
b = a + b;
a = b - a;
}
coEnd;
return -1;
}
int main() {
for (int i = 0; i < 10; i++) {
printf("%d, ", fib());
}
return 0;
}
又要被 C 语言老师追着打了……