Go

goroutine + sync.WaitGroup

admin by @admin ADMIN
just now
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`go fn()` spawns a goroutine. To wait for several to finish, use `sync.WaitGroup` — call `Add` before spawning, `Done` (deferred) inside, `Wait` to block until all are done.
Go
Raw
package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup
    urls := []string{"a", "b", "c", "d"}

    for _, u := range urls {
        wg.Add(1)                              // increment BEFORE go
        go func(url string) {
            defer wg.Done()                    // decrement when goroutine exits
            time.Sleep(100 * time.Millisecond)
            fmt.Println("fetched", url)
        }(u)                                   // pass `u` as arg — avoid closure capture bug
    }

    wg.Wait()                                  // blocks until all Done() called
    fmt.Println("all done")
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.