liveBook · Manning

Parallel loop

As explained in Learn Concurrent Programming with Go

Loop-level parallelism is a pattern that executes independent loop iterations concurrently or in parallel.

A parallel loop turns independent iterations into concurrent tasks, allowing different parts of a collection to run at the same time. In Go, each iteration can launch a goroutine, while a wait group keeps main from finishing before the work completes. section 10.2.1

Hashing files concurrently

A directory-hashing program reads the files, skips directories, and starts one goroutine per file. Each goroutine computes and prints its file's SHA-256 hash; sync.WaitGroup coordinates completion. Output order can vary because the hashes finish independently.

Apply the pattern when these conditions hold:

  • Use parallel iterations when one task's result does not affect another task's computation. section 10.2.1
  • Check for loop-carried dependence: an iteration depends on a step from another iteration in the same loop. section 10.2.1
  • Preserve dependent ordering by splitting work into parallel and synchronized parts, rather than parallelizing the shared update itself. section 10.4
  • Balance granularity: finer tasks increase parallelism but add synchronization and communication, while coarser tasks reduce that overhead. section 10.4

How Learn Concurrent Programming with Go covers it

How deep it goes
Explains goroutine and wait-group mechanics, loop-carried dependence, ordering, and granularity trade-offs.
Examples
Uses concurrent per-file SHA-256 hashing and sequential directory hashing with a loop-carried dependency.
What it assumes
Assumes basic Go functions and loops while introducing goroutines, wait groups, channels, and loop-carried dependence.
What you can do after
Builds a Go program that launches independent loop iterations concurrently and waits for their completion.
How it connects
Connects loop-level parallelism with task decomposition, data decomposition, dependency graphs, fork/join, worker pools, and pipelines.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Concurrent Programming with Go. The section links point to the parts of the book it draws on.