Goroutines and the go statement
- Version
- 1.27
- Review
- Draft
Summary#
A go statement starts a function call in a new goroutine and continues without waiting. The function value and arguments are evaluated first, in the calling goroutine. Return values are discarded, so send results over a channel or another synchronized path.
Syntax#
go process(item)
go func() { process(item) }()
Example#
package main
import "fmt"
func square(n int, out chan<- int) {
out <- n * n
}
func main() {
results := make(chan int)
n := 3
go square(n, results) // n is evaluated here
n = 10
fmt.Println(<-results, n)
done := make(chan struct{})
go func() {
defer close(done)
fmt.Println("worker finished")
}()
<-done
}
Expected output#
9 10
worker finished
Common mistakes#
The program exits when main returns, without waiting for other goroutines. Wait with a channel or sync.WaitGroup instead of sleeping. A goroutine blocked on an operation that can never complete stays leaked, so give each one a way to finish.
Version applicability#
The go statement works this way from Go 1.0. The goroutineleak profile in runtime/pprof was experimental in Go 1.26 and generally available in Go 1.27. It detects many leaked goroutines, though not all of them.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0