} int main(void) { /* The stack for the iterator function. */ char iterator_stack[SIGSTKSZ]; /* Flag indicating that the iterator has completed. */ volatile int iterator_finished; getcontext(&loop_context); /* Initialise the iterator context. uc_link points to main_context1, the * point to return to when the iterator finishes. */ loop_context.uc_link = &main_context1; loop_context.uc_stack.ss_sp = iterator_stack; loop_context.uc_stack.ss_size = sizeof(iterator_stack); /* Fill in loop_context so that it makes swapcontext start loop. The * (void (*)(void)) typecast is to avoid a compiler warning but it is * not relevant to the behaviour of the function. */ makecontext(&loop_context, (void (*)(void)) loop, 3, &loop_context, &main_context2, &i_from_iterator); /* Clear the finished flag. */ iterator_finished = 0; /* Save the current context into main_context1. When loop is finished, * control flow will return to this point. */ getcontext(&main_context1); if (!iterator_finished) { /* Set iterator_finished so that when the previous getcontext is * returned to via uc_link, the above if condition is false and the * iterator is not restarted. */ iterator_finished = 1; while (1) { /* Save this point into main_context2 and switch into the iterator. * The first call will begin loop. Subsequent calls will switch to * the swapcontext in loop. */ swapcontext(&main_context2, &loop_context); printf("%d\n", i_from_iterator); } } return 0; } NOTE: this example is not correct, but may work as intended in some cases. The function makecontext requires additional parameters to be type int, but the example passes pointers. Thus, the example may fail on 64-bit machines (specifically LP64-architectures, where sizeof(void*) > sizeof(int)). This problem can be worked around by breaking up and reconstructing 64-bit values, but that introduces a performance penalty. For get and set context, a smaller context can be handy: #include <stdio.h> #include <ucontext.h> #include <unistd.h> int main(int argc, const char *argv[]){ ucontext_t context; getcontext(&context); puts("Hello world"); sleep(1); setcontext(&context); return 0; } This makes an infinite loop because context holds the program counter. References External links System V Contexts - The GNU C Library Manual Unix Control flow C (programming language) libraries Articles with example C code Threads (computing)