Skip to content

Instantly share code, notes, and snippets.

@Preetam
Created March 12, 2014 17:51
Show Gist options
  • Save Preetam/9512327 to your computer and use it in GitHub Desktop.
Save Preetam/9512327 to your computer and use it in GitHub Desktop.
/*
$ cc context.c && ./a.out
foo() - 1
bar() - 1
foo() - 2
bar() - 2
foo() - 3
bar() - 3
bar() - 4
foo() - 4
*/
#include <ucontext.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
void
foo(ucontext_t* thisctx, ucontext_t* nextctx) {
printf("foo() - 1\n");
swapcontext(thisctx, nextctx);
printf("foo() - 2\n");
swapcontext(thisctx, nextctx);
printf("foo() - 3\n");
swapcontext(thisctx, nextctx);
printf("foo() - 4\n");
swapcontext(thisctx, nextctx);
}
void
bar(ucontext_t* thisctx, ucontext_t* nextctx) {
printf("bar() - 1\n");
swapcontext(thisctx, nextctx);
printf("bar() - 2\n");
swapcontext(thisctx, nextctx);
printf("bar() - 3\n");
swapcontext(thisctx, nextctx);
printf("bar() - 4\n");
swapcontext(thisctx, nextctx);
}
int
main() {
const STACK_SIZE = 512;
ucontext_t foo_ctx, bar_ctx, blank_ctx;
uint8_t foo_stack[STACK_SIZE];
uint8_t bar_stack[STACK_SIZE];
getcontext(&foo_ctx);
foo_ctx.uc_stack.ss_sp = foo_stack;
foo_ctx.uc_stack.ss_size = STACK_SIZE;
getcontext(&bar_ctx);
bar_ctx.uc_stack.ss_sp = bar_stack;
bar_ctx.uc_stack.ss_size = STACK_SIZE;
makecontext(&foo_ctx, foo, 2, &foo_ctx, &blank_ctx);
makecontext(&bar_ctx, bar, 2, &bar_ctx, &blank_ctx);
swapcontext(&blank_ctx, &foo_ctx);
swapcontext(&blank_ctx, &bar_ctx);
swapcontext(&blank_ctx, &foo_ctx);
swapcontext(&blank_ctx, &bar_ctx);
swapcontext(&blank_ctx, &foo_ctx);
swapcontext(&blank_ctx, &bar_ctx);
swapcontext(&blank_ctx, &bar_ctx);
swapcontext(&blank_ctx, &foo_ctx);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment