IT lexicon › Programming › Protothreads

Protothreads

Programming På svenska → Updated: 2026-11-03

Stackless pseudo-threads in plain C, built from a macro trick, that make event-driven code read sequentially for two bytes of RAM per thread.

Adam Dunkels presented the technique at SenSys 2006 with Oliver Schmidt, Thiemo Voigt and Muneeb Ali, and it became a cornerstone of Contiki. The macros PT_BEGIN, PT_WAIT_UNTIL and PT_END expand into a switch statement that remembers the line number where the function last left off. The next call jumps straight back there — the same family of abuse as Duff's device. It reads like a blocking thread, but is really a function that returns and gets called again.

The bill is plain. Local variables do not survive a wait, because there is no stack to keep them on, and you cannot use a switch statement of your own unless you pick the variant based on GCC's labels-as-values. The idea lives on in the stackless coroutines of C++20 and Rust, which perform the same transformation with the compiler's help instead of the preprocessor's.

← Back to the lexicon