C Programming/Coroutines

From Wikibooks, the open-content textbooks collection

Jump to: navigation, search

A little known fact is that most C implementations have builtin primitives that can be used for cooperive multitasking / coroutines. They are Setcontext and setjmp.

[edit] setjmp

The function setjmp is used in a pair with longjmp to transfer execution to a different point in the code. It relies on an existing jmp_buf declaration.

#include <setjmp.h>
 
int main (void)
{
  jmp_buf buf1;
 
  if (setjmp(buf1) == 0)
  {
    /* This code is executed on the first call to setjmp. */
 
    longjmp(buf1, 1);
  } else {
    /* This code is executed once longjmp is called. */
  }
  return 0; 
}

setjmp() stores the current execution point in memory, which remains valid as long as the containing function doesn't return. It initially returns 0. Control is returned to setjmp once longjmp is called with the original jmp_buf and the replacement return value.

Note that jmp_buf is passed to setjmp without using the address-of operator.