Sending values between goroutines
In the last lesson, goroutines wrote their results through pointers, and a WaitGroup told main when they were done. Go has a second tool for this, and it is used even more often: the channel. A channel is like a pipe between goroutines. One goroutine puts a value in, and another takes it out.
You make a channel with make, and you say what type of value it carries:
package main
import "fmt"
func double(n int, out chan int) {
out <- n * 2
}
func main() {
results := make(chan int)
go double(21, results)
answer := <-results
fmt.Println(answer)
}
Output:
42
The arrow <- shows which way the value moves:
| Code | Meaning |
|---|---|
out <- n * 2 | send: put the value into the channel |
answer := <-results | receive: take a value out of the channel |
results and out are the same channel. main passed it to double as an argument.
A channel makes goroutines wait
There is no WaitGroup in that program, and still main did not end too early. Why? A receive waits until a value arrives. So answer := <-results paused main until double sent its result.
A send waits too. With a channel made by make(chan int), a send waits until another goroutine is ready to receive. The two goroutines meet, the value passes, and then both go on.
Deadlock
If a send can never be received, it waits forever. Here main sends, but no other goroutine exists to receive:
package main
import "fmt"
func main() {
ch := make(chan int)
ch <- 5
fmt.Println(<-ch)
}
Output:
fatal error: all goroutines are asleep - deadlock!
The send on line 7 waits for a receiver, so the receive on line 8 is never reached. Go sees that every goroutine is waiting and nothing can ever change, so it stops the program. This is called a deadlock.
Several values in order
A goroutine can send many values through the same channel. Values sent by one goroutine arrive in the order they were sent:
words := make(chan string)
go func() {
words <- "one"
words <- "two"
words <- "three"
}()
for i := 0; i < 3; i++ {
fmt.Println(<-words)
}
Output:
one
two
three
main receives three times because it knows three values are coming. The next lesson shows how a sender can say "no more values" instead.
Two goroutines, one channel
Several goroutines can send into one channel. Here two goroutines each send a square:
package main
import "fmt"
func square(n int, out chan int) {
out <- n * n
}
func main() {
results := make(chan int)
go square(3, results)
go square(4, results)
a := <-results
b := <-results
fmt.Println(a + b)
}
Output:
25
a could be 9 or 16. It depends on which goroutine finishes first, and that can change between runs. But a + b is always 25, so the output is always the same. When results arrive in an unknown order, combine them in a way where the order does not matter.
In the exercise, two goroutines each sum half of the numbers. Receive both sums from the channel and print their total.