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
