Skip to content

Instantly share code, notes, and snippets.

@mrtrizer
Last active November 2, 2022 12:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrtrizer/a14c033a054c191d9d23bfa516ad8107 to your computer and use it in GitHub Desktop.
Save mrtrizer/a14c033a054c191d9d23bfa516ad8107 to your computer and use it in GitHub Desktop.
C language coroutine with switch-case
#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