A WaitGroup coordinates concurrent work when one goroutine must start several others and wait until every task finishes. It is useful when independent jobs, such as file compression, should run in parallel before a summary is displayed. section 5.2.1
Use the synchronization count around each worker:
- Create a sync.WaitGroup. section 5.2.1
- Call Add(1) before launching each goroutine. section 5.2.1
- Call Done when the worker completes. section 5.2.1
- Call Wait in the coordinating goroutine before continuing. section 5.2.1
Listing 5.3 Compressing files in parallel with a wait group
package main
import (
"compress/gzip"
"fmt"
"io"
"os"
"sync"
)
func main() {
var wg sync.WaitGroup #1
for i, file := range os.Args[1:] {
wg.Add(1) #2
go func(filename string) { #3
compress(filename) #3
wg.Done() #3
}(file) #4
}
wg.Wait() #5
fmt.Printf("Compressed %d files\n", len(os.Args[1:]))
}
func compress(filename string) error {
// Unchanged from above
}
A complete parallel file-compression example applies Add, launches workers, signals Done, waits for completion, and prints the compressed-file count. section 5.2.1




