Have you ever played one of those neat, new, sophisticated video games and wondered how it works? How it was written? How the game flies alien spaceships across the screen, fires tracking missiles whenever you hit the phaser button, and blows away the universe when missile and enemy collide? It's a screen full of many independent activities going on at once, yet synchronizing at just the right moment to give the video game its magic!
Video games are complex systems. They involve many asynchronous entities (the missiles, the alien ships, even your own ship) which must synchronize on both internal events (collisions) and external ones (button presses). They can be challenging to play, and even more challenging to write, unless you possess the right abstractions...
Programs like video games with many independent entities do not readily decompose into operations and sub-operations, into a single hierarchal task. A sequential nor a functional flow doesn't seem to fit. As in life, things are naturally going on in parallel, and even if you have only one person (or processor) to do them, you find there are other things you can do while waiting for something else. Often, whether building operating systems or modeling space wars, the problem decomposes into many, independent tasks, each living asynchronously in its own context...
IN THIS ARTICLE we will explore these contexts in which a thread of program control executes. Fundamental to the idea of multitasking is the ability to begin, restart & suspend, and finally end threads of execution. The context switch we explore here packs such flow control into a single construct, and offers it to the programmer in a familiar form: the function call. Currently running on both Berkeley 4.3 UNIX and MS-DOS, its ``C'' implementation is highly portable, and its clean functionality reduces the need for grungy machine-dependent code on higher levels. Subsequent articles will build upon this flexibility and power to construct a multitasking and potentially multiprocessing environment within ``C''; based on the context switch, the environment would be portable to both UNIX and MS-DOS, and provide both interprocess communication and resource management –in other words, lots of power for programs. Sounds like fun? Then let's get started!