Coroutines in C

Simon Tatham has an interesting variation on Duff's device, used to mimic coroutines in C. The guts are hidden inside macros, so the resulting code actually reads quite cleanly. Something to consider next time you find yourself writing a large state machine, wishing you didn't have to turn all your control statements inside out. Here's an example of the result:


int decompressor(void) {
static int c, len;
crBegin;
while (1) {
c = getchar();
if (c == EOF)
break;
if (c == 0xFF) {
len = getchar();
c = getchar();
while (len--)
crReturn(c);
} else {
crReturn(c);
}
}
crReturn(EOF);
crFinish;
}

He points out that the requirement to use static variables can be got around by the standard technique of passing a struct holding all the state. But if you follow this train of thought a bit further, you realize that the technique is even better in C++, where the state is accessible via the "this" pointer:

class Decompressor {
private:
     int c, len;
public:
     int read() {
         crBegin();
         while (1) {
             c = getchar();
             if (c == EOF)
                 break;
             if (c == 0xFF) {
                 len = getchar();
                 c = getchar();
                 while (len--)
                     crReturn(c);
             }
             else {
                 crReturn(c);
             }
         }
         crReturn(EOF);
         crFinish;
     }
}

The C++ version also gives the ability to initialize the state in the constructor, instead of requiring a special initialization call by the client.

Posted on May 26, 2003 03:33 PM
More languages articles

Comments
Post a comment









Remember info?




Prove you're human. Type "human":