Go · Level 3 Concurrency

Goroutines and WaitGroup

Call several services at the same time with goroutines in Go, wait for all of them with sync.WaitGroup, and return the results in the original order.

  • go f() runs f concurrently
  • WaitGroup: Add, Done, Wait
  • write results by index, in order

go f() runs f concurrently. A sync.WaitGroup waits for goroutines: Add(1) before starting each, Done() when it ends, Wait() to block until all are done. Trap: without Wait, you return before the goroutines finish.

var wg sync.WaitGroup
for i := 0; i < 3; i++ {
    wg.Add(1)
    go func(n int) {
        defer wg.Done()
        work(n)
    }(i)
}
wg.Wait()

Write FetchAll(urls []string, fetch func(string) int) []int: call fetch for every URL, each in its own goroutine, and return the results in the order of urls. Example: with fetch returning the length, [a bb ccc] → [1 2 3].

solution.go
Test Suites Pending
Output