Protothreads with Local Continuations

Hard C Concurrency Asked at Espressif Systems
Solve this problem

Implement stackless coroutines in C using the switch-based protothread trick, so a state machine can be written as straight-line blocking code without an RTOS.

Constraints

  • PT_BEGIN, PT_WAIT_UNTIL, PT_YIELD and PT_END macros.
  • State is a single integer per thread - no per-thread stack.
  • Local variables do not survive a yield; that limit must be documented.
  • A thread resumes exactly where it yielded.
  • No dynamic memory, no setjmp.
  • Must work with a plain C compiler.
Starter codeC
1typedef struct { unsigned short line; } pt_t;2 3// TODO: PT_BEGIN, PT_WAIT_UNTIL, PT_YIELD, PT_END