Upgrade to Pro — share decks privately, control downloads, hide ads and more …

C Coroutine

C Coroutine

Chein-Wei Huang

August 06, 2015
Tweet

More Decks by Chein-Wei Huang

Other Decks in Technology

Transcript

  1. Process, Thread, Event • Process & Thread ◦ Resource cost

    ◦ Resource lock ◦ process1/thread1(io1,do1), process2/thread2(io2, do2) • Event ◦ Lots of nested callbacks ◦ set(io1,do1); set(io2,do2); loop_event();
  2. Coroutine foo() { static int i; for(i = 0; i

    < 10; i++){ printf(“%d\n”, i); yield i; } } foo(); // 0 foo(); // 1
  3. Coroutine a() { a_init(); while(!io1()) yield; do1(); } b() {

    b_init(); while(!io2()) yield; do2(); } loop{a(); b();};
  4. C Coroutine Library • Protothread ◦ switch case • State

    threads ◦ longjmp + setjmp • couroutine ◦ ucontext
  5. Protothread int function(void) { static int i, state; switch (state)

    { case 0: /* start of function */ for (i = 0; i < 10; i++) { state = __LINE__ + 2; /* so we will come back to "case __LINE__" */ return i; case __LINE__:; /* resume control straight after the return */ } } }