Go by Example

Goroutines

Launch concurrent function calls with the go keyword and wait for them to finish safely.

A goroutine is a function call that can run while its caller continues. Put go before a call to start it. A sync.WaitGroup is a counter that lets the caller wait until started tasks finish.

Add to the wait group before starting the goroutine. Call Done when it finishes, then wait in main.

package main
 
import (
    "fmt"
    "sync"
)
 
func main() {
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        fmt.Println("working")
    }()
    wg.Wait()
    fmt.Println("finished")
}

In production

Goroutines are inexpensive to start, but one waiting for input still uses memory and may keep resources open. Limit how many you start when work arrives faster than it finishes. Give tasks a way to stop when the code that started them is done.

Enjoyed this? Get more software craft delivered to your inbox.