GO / CHAPTER 12
Goroutines and channel coordination
AdvancedCoordinate a small concurrent computation without guessing scheduling order.
By the end of this chapter
- Start a goroutine
- Send and receive a typed value
- Recognize blocking and lifetime requirements
The idea
Enter with functions and blocking operations understood. A go statement starts a goroutine that can execute concurrently with its caller. Its execution order relative to other goroutines is not a reliable basis for program logic. The process exits when main returns, so background work needs explicit coordination if its result matters. Avoid using a delay as a substitute for a completion contract.
A channel transports typed values between goroutines. With an unbuffered channel, a send and a matching receive coordinate with one another; the send cannot complete without a receiver. The example has one producer and one receive, making its printed value deterministic despite flexible scheduling. Larger designs need ownership of channel closing and cancellation behavior. A receiver should not close a channel while a producer may still send to it.
package main
import "fmt"
func main(){
result:=make(chan int)
go func(){result<-6*7}()
fmt.Println(<-result)
}42
Main waits for the received value before printing and returning. The producer’s calculation is independent of scheduling order.
Try it yourself
Send the sum of a borrowed input slice from one goroutine and wait for the result in main, without modifying the slice concurrently.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING