Goroutines
Launch concurrent function calls with the go keyword and wait for them to finish safely.
A goroutine is a function call that runs concurrently with the caller. The go statement starts one, and the caller continues without waiting. A sync.WaitGroup lets the caller wait for work to 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 have low startup cost, but a blocked goroutine still uses memory and may hold resources. Bound concurrency when work can arrive faster than it completes, and provide cancellation for work that should stop when its owner exits.
Enjoyed this? Get more software craft delivered to your inbox.