Friday, September 08, 2006

Having fun with a switch


Have you had fun with a switch lately?
There is a thing called the Duff device. This is a C programmers dream and the reviewers nightmare. Some say it's abusing the language and some say it's beautiful. Myself I see beauty in most things.

This is how the Duff device looks like

switch (count % 8) /* count > 0 assumed */
{
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);
}



So what good can you do with a thingy like this? You can actually produce your own lightweight threads library using this construction. Just look at this

#include "pt.h"

struct pt pt;
struct timer timer;

PT_THREAD(example(struct pt *pt))
{
PT_BEGIN(pt);

while(1) {
if(initiate_io()) {
timer_start(&timer);
PT_WAIT_UNTIL(pt,
io_completed()
timer_expired(&timer));
read_data();
}
}
PT_END(pt);
}

Example protothreads code.


This is 100% pure C. The macros actually build a kind of Duff device that incorporates the __LINE__ macro in an ingenious way. If you are interested take a look at http://www.sics.se/~adam/pt/



No comments: