Last active
November 2, 2022 12:12
-
-
Save mrtrizer/a14c033a054c191d9d23bfa516ad8107 to your computer and use it in GitHub Desktop.
C language coroutine with switch-case
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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#define COROUTINE_START(line) switch (line) { case 0: | |
#define WAIT_WHILE(condition) return __LINE__; case __LINE__: if (condition) return __LINE__; | |
#define COROUTINE_END default: return -1; } | |
int coroutine(int handle, | |
struct { | |
int counter; | |
int i; | |
}* state) | |
{ | |
COROUTINE_START(handle); | |
printf("Initialization\n"); | |
for (state->i = 0; state->i < 3; state->i++) { | |
state->counter = 0; | |
WAIT_WHILE(state->counter++ < 5); | |
printf("Some code in the middle 1\n"); | |
} | |
WAIT_WHILE(state->counter++ < 10); | |
printf("Some code in the middle 2\n"); | |
WAIT_WHILE(state->counter++ < 15); | |
printf("Finalization\n"); | |
COROUTINE_END; | |
} | |
int main(void) | |
{ | |
char state[256] = {0}; | |
int line = 0; | |
while (line != -1) | |
{ | |
line = coroutine(line, (void*)state); | |
printf("%d\n", line); | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment