Software-Driven Switching $\Longleftarrow$ Interprocess Communication

As an example, I constructed a simple ``C'' program which puts the thread cluster to good use. It creates three threads, all of which evaluate the same thread function, but distinguish themselves by variables stored on their local heap by their creator. The three threads switch between each other in a circular fashion, each printing out its name on the screen when it is invoked. Finally, one by one, the counter in each of the threads expires, and the threads ``return'' back to the thread which first ``called'' them until the main thread is reached and the program terminates. This program provides a simple example of threads in action, and is a good thing to run to insure your installation of the thread cluster is running properly.

As a more sophisticated example (and a suitable challenge for the video game goer), the thread cluster could be used to set up a simple robot video game. In this game, each player can program his or her own robot as an independent program (the only difference it's ``main'' procedure would actually be a THDFN). Each robot would call upon a set of shared library functions (botmove, botseek, botshoot, etc) to hunt down and try to destroy other robots – but meanwhile, the other robots will be trying to do the same.

The trick is when a robot calls a library function, before returning the function will call a simple scheduler to switch to another robot in a (transparent) round-robin fashion. After each trip around this circular queue of robots, the scheduler would temporarily switch to the real main thread of the robot game. The real main thread would look over the damage had been done: arbitrating collisions, disposing of any dead robots and expired missiles, moving the survivors along to where they wanted to go, and redisplaying the battlefield. If there are any robots left, the main task could then switch back to the scheduler to begin another round.

With multiple threads and context switching, the implementation of such a game not be that difficult, as we could treat robots, missiles and everything that moves on its own as an independent thread. Thus robots could shoot guided missiles with smart tracking programs. And these missiles themselves could shoot off more, smaller proj*. Or, if you really want to get sophisticated, ally 'bots could send homing birds carrying messages of enemy movements! It's exciting how a good programming concept like context context switching can really spice up a game.