Skip to content

Instantly share code, notes, and snippets.

@yefremov
Created July 3, 2017 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yefremov/5a545874a2adde7b2385cc0bbf484a08 to your computer and use it in GitHub Desktop.
Save yefremov/5a545874a2adde7b2385cc0bbf484a08 to your computer and use it in GitHub Desktop.
Coroutines in C (go macros)
//
// 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