Skip to content

Approach 1: Heap Allocation per Iteration ​

Task ​

Implement the parallel Game of Life so that in every iteration, each worker goroutine allocates new memory on the heap for the horizontal strip it computes. The worker reads the previous state of the board, writes the new state of its strip into the memory it has just allocated, and returns that strip to the distributor. The distributor assembles the strips into the board for the next iteration.

How an iteration flows ​

world tshared, read-onlyworker 0: make(strip)rows 0..a, new heap memoryworker 1: make(strip)rows a..b, new heap memoryworker 2: make(strip)rows b..H, new heap memoryresult channelsworld t+1assembled from stripsworld t is nowunreferenced →GCThe distributor assembles the strips into the next board.

Requirements ​

  • Exactly gol.Params.Threads workers, each owning one horizontal strip. Strip heights should differ by at most one row, including when the height is not a multiple of the worker count.
  • New memory for each worker's strip is allocated inside the iteration loop, not once at start-up.
  • Workers must not modify the board that other workers are reading.
  • Correct handling of the board edges (the world wraps around).
  • 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
DistributorHands the current board to the workers each iteration, collects their strips, and assembles the next board.
WorkersAllocate memory for their strip, compute it from the previous board, and return it.
CommunicationChannels between the distributor and the workers. You choose what travels over them.

Suggested steps ​

  1. Start from your Step 2 worker-pool implementation and note where its output memory is currently allocated.
  2. Change the workers so that each iteration they allocate their own output and return it, rather than writing into shared storage.
  3. Change the distributor so that the next board is built from the returned strips.
  4. 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.