Skip to content

Approach 2: Double Buffering ​

Task ​

Implement the parallel Game of Life using two boards that are allocated once: a source and a destination. In every iteration the workers read from the source and write their results into the destination. After the iteration, the pointers to source and destination are switched, so the destination becomes the source for the next iteration. No board is allocated or copied during the run.

Visualisation ​

Step through one iteration. Colours show which worker wrote each cell of the destination board.

turn 0
Buffer A · SRC
Buffer B · DST

Phase 1/3. Turn begins. Workers will read SRC (everything) and write only their own rows of DST. DST currently holds stale data.

Requirements ​

  • Both boards are allocated up front; steady-state iterations perform no per-iteration board allocations.
  • Exactly gol.Params.Threads workers, each responsible for a horizontal strip of the destination.
  • The source and destination pointers are switched once per iteration.
  • Correct handling of the board edges (the world wraps around), including rows that lie in a neighbouring worker's strip.
  • All of the features from Steps 3 to 6 keep working: the ticker, PGM output, keyboard controls and SDL events.
  • Passes all tests, including with -race.

Components to build ​

ComponentResponsibility
Two boardsAllocated once, before the first iteration. One is the source, the other the destination.
DistributorStarts each iteration, waits for it to finish, and performs the switch.
WorkersCompute their strip of the destination from the source.
CommunicationWhatever you need to start an iteration and to learn that it has finished. You choose the mechanism.

Suggested steps ​

  1. Allocate the two boards and copy the initial state into the source.
  2. Give each worker access to both boards and a strip to be responsible for.
  3. Run one iteration with a single worker and compare against your baseline.
  4. Add the switch and run many iterations; then increase the number of workers.
  5. Re-run the full test-suite, including -race, after each change.

Analysis questions, benchmarks and report guidance for this approach are in Benchmarking and Testing.