20 Threads
This chapter covers
- Interthread control
- Initializing and destroying threads
- Working with thread-local data
- Critical data and critical sections
- Communicating through condition variables
Threads are another variation of control flow that allows us to pursue several tasks concurrently. Here, a task is a part of the job to be executed by a program such that different tasks can be done with no or little interaction between each other.
Our main example will be a primitive game that we call B9
, which is a variant of Conway's Game of Life, (see Gardner (1970)). It models a matrix of primitive “cells” that are born, live, and die according to very simple rules. We divide the game into four different tasks, each of which proceeds iteratively. The cells go through life cycles that compute birth or death events for all cells. The graphical presentation in the terminal goes through drawing cycles, which are updated as fast as the terminal allows. Spread between these are user keystrokes that occur irregularly and allow the user to add cells at chosen positions. Figure 20.1 shows a schematic view of these tasks for B9
.
Figure 20.1 Control flow of the five threads of B9

The four tasks are