Skip to main content.
October 19th, 2005

The Infernal State Machine and the Coroutines

Not long ago I complained on how painful it is to deal with state machines.
With video-games more than some other kind of software, there is a need to run concurrent threads. Multiple tasks that progressively do things over a larger amount of time.
Normally one programs thinking of one routine at the time. The flow of the code is meant to start in the routine and end with it.
I don’t have much time to make a decent example.. I’ll just say that generally one ends up with big switch statements;

Something like:

    switch ( state )
    {
    case IDLE:
         break;
    case CREATE_CONNECTION:
         // …
         if ( done )
             state = CONNECTING;
         break;
    case CONNECTING:
         // …
         if ( done )
             state = TRANSMIT;
         break;
    case TRANSMIT:
         // …
         if ( done )
             state = DISCONNECT;
         break;
    case DISCONNECT:
         // ………
         if ( done )
             state = IDLE;
         break;
     }}


Which looks tidy in this example, until one gets into a practical application, with the state machine jumping from one state to another… it can get pretty messy !!!

So, how to simplify all this ? Given the limitation of the language (C/C++).
The solution is pretty simple.. and it comes from the plain old C hacking with the freedom that the language gives, and with the preprocessor. A very low tech solution, far from what one would think.. in this day of age with all those fancy C++ template code.
This hack has a name, it’s called coroutines. A proper explanation can be read at the link provided.

I’m pretty excited about this, but I haven’t had time to really test the usability on relatively complex cases yet.

Almost time to zzzzz !

Posted by Davide Pasca in Uncategorized

This entry was posted on Wednesday, October 19th, 2005 at 2:52 am and is filed under Uncategorized. You can follow any responses to this entry through the comments RSS 2.0 feed. You can leave a response, or trackback from your own site.

4 Responses to “The Infernal State Machine and the Coroutines”

  1. rince says:

    you are crazy mf! or is it co-mf??

  2. Davide Pasca says:

    Leave that co-routine alone mf !!

  3. ragin' lion says:

    You might want to take a look at Protothreads. Save yourself some pain. 8P

  4. Davide Pasca says:

    I got to the Coroutines starting from the Protothreads actually.
    I really cared to find the hack. The Protothread is a formal implementation with some added fanciness which I currently don’t need.
    In any case, the actual “library code” of Protothreads is around 50 lines of macros 8)

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>