c coroutine

9
C Coroutine Multiple tasks with single CPU

Upload: chien-wei-huang

Post on 21-Jan-2017

295 views

Category:

Software


0 download

TRANSCRIPT

Page 1: C coroutine

C CoroutineMultiple tasks with single CPU

Page 2: C coroutine

Outline

1. Process, Thread, Event2. Coroutine3. C Couroutline Library 4. Protothread5. Reference

Page 3: C coroutine

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();

Page 4: C coroutine

Coroutinefoo() {

static int i;for(i = 0; i < 10; i++){

printf(“%d\n”, i);yield i;

}}

foo(); // 0foo(); // 1

Page 5: C coroutine

Coroutinea() {

a_init();while(!io1()) yield;do1();

}b() {

b_init();while(!io2()) yield;do2();

}loop{a(); b();};

Page 6: C coroutine

C Coroutine Library

● Protothread○ switch case

● State threads○ longjmp + setjmp

● couroutine○ ucontext

Page 7: C coroutine

Protothreadint 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 */

}

}

}

Page 8: C coroutine

Protothread