typestar

Goroutines and WaitGroup in Go

Starting concurrent work and waiting for it.

func fanOut(jobs []string) {
    var wg sync.WaitGroup
    for _, job := range jobs {
        wg.Add(1)
        go func(name string) {
            defer wg.Done()
            fmt.Println("working on", name)
        }(job)
    }
    wg.Wait()
}

How it works

  1. go func() launches a goroutine.
  2. wg.Add/wg.Done track outstanding work.
  3. wg.Wait blocks until every goroutine finishes.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
179
Tokens
60
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 38 seconds.

Type this snippet

Step 1 of 3 in Goroutines, step 1 of 25 in Concurrency.

Next →