Sto leggendo da un paio di orette come funziona il meccanismo dei protothread ma non riesco a capire il funzionamento del dispositivo di Duff.
http://groups.google.com/group/comp.lang.c/msg/bb78298175c42411?dmode=source
http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
Nei protothread è usato per creare questo switch:
char example(struct pt *pt)
{
switch(pt->lc) { case 0:
while(1) {
pt->lc = 12; case 12:
if(!(counter == 1000)) return 0;
printf("Threshold reached\n");
counter = 0;
}
} pt->lc = 0; return 2;
}
L'autore dice poi:
Did you notice anything slightly strange with the code above? The switch(pt->lc) statement jumped right into the while(1) loop. The case 12: statement was inside the while(1) loop! Does this really work? Yes, it does in fact work! This feature of the C programming language was probably first found by Tom Duff in his wonderful programming trick dubbed Duff's Device. The same trick has also been used by Simon Tatham to implement coroutines in C (a terrific piece of code).
Arrivo al fatto che il case 0 viene eseguito subito e cambia state a 12. Ma perché dopo salta dentro al secondo switch?
Anche il dispositivo originale di Duff non mi è chiaro:
switch (count % 8) {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while ((count -= 8) > 0);
}