6.2 Threads

All code that runs under the operating system, runs in the same address space. That is, the game runs as one process. While it is possible to structure a game application as one monolithic program, it is usually advantageous to subdivide it into smaller, more manageable subprograms called threads. With its own stack, each thread usually performs one function, often repetitively. This subdivision leads to simplicity for each thread. Thus, it is easier to understand the structure of the program and to minimize interference between threads. The threads section describes these threads, how they are scheduled, and how various operations may be performed on them.

Threads may be created, destroyed, stopped, or blocked (the latter by waiting on a message). Threads normally run until they require some resource or event to continue, at which point they yield the CPU to another thread. Each thread has an assigned priority level, used to determine which thread has access to the CPU at any given time. In response to an external event, a thread may be forced to yield control of the CPU. The operating system preserves the state of the thread properly for restarting at a later time. Thus, the system can be described as preemptive. Threads may even be preempted during system calls when preemption will not cause any problems.

There is no concept of a swap clock or "round-robin" scheduling as is found in UNIX and other time-sharing systems. Thus, two or more threads that run at the same priority level do not alternate in use of the CPU. The thread that "has" the CPU runs until it yields or is preempted by a higher priority thread in response to an exception.

UP