Chapter 18. Threads


This chapter covers

  • Inter-thread 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 allow us to pursue several tasks concurrently. Here, a task is a part of the job that is to be executed by a program such that different tasks can be done with no or little interaction between each other.

Our main example for this will be a primitive game that we call B9 that 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 that allow the user to add cells at chosen positions. Figure 18.1 shows a schematic view of these tasks for B9.

The four tasks are:

18.1. Simple inter-thread control

18.2. Race-free initialization and destruction

18.3. Thread-local data

18.4. Critical data and critical sections

18.5. Communicating through condition variables

18.6. More sophisticated thread management