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.
Requirements
- Both boards are allocated up front; steady-state iterations perform no per-iteration board allocations.
- Exactly
gol.Params.Threadsworkers, 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
| Component | Responsibility |
|---|---|
| Two boards | Allocated once, before the first iteration. One is the source, the other the destination. |
| Distributor | Starts each iteration, waits for it to finish, and performs the switch. |
| Workers | Compute their strip of the destination from the source. |
| Communication | Whatever you need to start an iteration and to learn that it has finished. You choose the mechanism. |
Suggested steps
- Allocate the two boards and copy the initial state into the source.
- Give each worker access to both boards and a strip to be responsible for.
- Run one iteration with a single worker and compare against your baseline.
- Add the switch and run many iterations; then increase the number of workers.
- 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.