Go — Goroutines and channel ownership
Use a channel to pass readings from a producer goroutine to a consumer and signal completion.
A simple example
Pass one number through a channel
- Start with A goroutine sends 2
- Do this Receive on the channel
- Result 2
package main
import "fmt"
func main() {
numbers := make(chan int)
go func() { numbers <- 2 }()
fmt.Println(<-numbers)
}
2
Collect results from a goroutine
An unbuffered channel synchronizes each send with a receive. The producer owns the close, and the consumer ranges until the channel closes. Leaving the producer open would keep the consumer waiting.
A worker sends visitor counts of 4 and 7 to the main program. The main program totals each count as it arrives. Closing the channel tells the receiver that the final total is eleven.
Run the example
Go 1.20 or later. Run these commands from the directory containing the example.
go run main.go
package main
import (
"fmt"
)
func main() {
readings := make(chan int)
go func() {
defer close(readings)
for _, n := range []int{4, 7} {
readings <- n
}
}()
total := 0
for n := range readings {
total += n
}
fmt.Println(total)
}
11
The sends deliver 4 and 7. Closing the channel allows the range loop to finish, so the result is 11 regardless of goroutine scheduling.
Try it yourself
What if the producer sends no values and closes the channel?
Check your answer
The range loop finishes immediately and the total is zero.