Created
July 3, 2017 20:28
-
-
Save yefremov/5a545874a2adde7b2385cc0bbf484a08 to your computer and use it in GitHub Desktop.
Coroutines in C (go macros)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// count.c | |
// | |
// Based on a a Duff's device | |
// https://pusher.com/sessions/meetup/the-realtime-guild/realtime-stream-processing-with-coroutines | |
// | |
#define go static int __resume__ = 0; \ | |
if (__resume__) goto __RESUME__; | |
#define yield(value) do { if (!__resume__) __resume__ = 1; \ | |
return value; __RESUME__:; } while (0) | |
/* | |
* Count numbers. | |
*/ | |
int | |
count() { | |
go { | |
static int n = 0; | |
while (1) { | |
yield(n++); | |
} | |
} | |
} | |
/* | |
* Run program. | |
*/ | |
int | |
main() { | |
printf("%d\n", count()); // 0 | |
printf("%d\n", count()); // 1 | |
printf("%d\n", count()); // 2 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment