3 ms·
By far my favorite trick is the one described here https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html https://www.chiark.greenend.org.uk/~sgtatham/cor
by adrusi 6y ago
By far my favorite trick is the one described here https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
Effectively generators a la python or javascript, implemented using a set of macros that expand to a Duff's device control structure.
#define crBegin(state) \
int *__state_ptr__ = &(state); \
*__state_ptr__ = 0; \
switch(*__state_ptr__) { case 0:
#define yield(x) \
do { \
*__state_ptr__ = __LINE__; \
return x; \
case __LINE__:; \
} while (0)
#define crFinish }
struct counter_frame {
int state;
int i;
};
int counter(struct counter_frame *frame) {
crBegin(frame->state);
frame->i = 0;
while (1) {
yield(frame->i++);
}
crFinish;
}
int main() {
struct counter_frame my_counter;
while (1) {
printf("%d\n", counter(&my_counter));
}
return 0;
}