c coroutine
TRANSCRIPT
C CoroutineMultiple tasks with single CPU
Outline
1. Process, Thread, Event2. Coroutine3. C Couroutline Library 4. Protothread5. Reference
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();
Coroutinefoo() {
static int i;for(i = 0; i < 10; i++){
printf(“%d\n”, i);yield i;
}}
foo(); // 0foo(); // 1
Coroutinea() {
a_init();while(!io1()) yield;do1();
}b() {
b_init();while(!io2()) yield;do2();
}loop{a(); b();};
C Coroutine Library
● Protothread○ switch case
● State threads○ longjmp + setjmp
● couroutine○ ucontext
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 */
}
}
}
Protothread
Reference
● http://programmers.stackexchange.com/questions/147182/
● http://coolshell.cn/articles/10975.html● http://coolshell.cn/articles/12012.html