A mutex guards one record that everyone uses, and goroutines take turns holding its lock. Go has another way: instead of sharing a record, goroutines send each other values through a channel, a typed pipe from one goroutine to another. Go's motto: "don't communicate by sharing memory, share memory by communicating".
At Bimo's Meatball Stall, a channel is the order queue between the till and the kitchen. The till (one goroutine) puts orders in, the kitchen (another goroutine) takes them out. There are two kinds of queue. With no tray, the cashier has to hand the bowl straight to the cook, so the two must meet first. With a tray of 3 places, the cashier may drop off up to 3 orders and go back to the customers. Those are unbuffered and buffered channels.
Making, sending, receiving
package main
import "fmt"
func main() {
queue := make(chan string)
go func() {
queue <- "tendon meatballs"
}()
order := <-queue
fmt.Println("kitchen got:", order)
}
$ go run stall.go
kitchen got: tendon meatballs
make(chan string)makes a channel that carriesstringvalues. A channel has a type: achan intonly takesint.- The
<-operator moves a value, and the direction of the arrow decides what it means.queue <- "tendon meatballs"sends into the channel;order := <-queuereceives from it. So forch := make(chan int), sending 42 is writtench <- 42. - Receiving waits too:
mainis held at<-queueuntil the till goroutine sends. That makes a channel another way to wait for a goroutine, besides a WaitGroup.
Unbuffered: they have to meet
A channel from make(chan string) has no room to store anything. The sender waits until there is a receiver, and the receiver waits until there is a sender. Once both are ready, the value moves and both carry on.
Guess: if queue := make(chan string) and then main goes straight to queue <- "tendon meatballs" with no other goroutine around, what happens?
The only goroutine is main, and it is the one waiting on the send line. Nobody will ever receive:
$ go run stall.go
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]:
main.main()
/home/bimo/stall/stall.go:7 +0x28
exit status 2
A deadlock: every goroutine is waiting on another and none can move. The Go runtime spots it, names the stuck goroutine and why (chan send), then stops the program.
Buffered: a tray with room
queue := make(chan string, 3)
queue <- "tendon meatballs"
queue <- "chicken noodles"
queue <- "iced tea"
fmt.Println("inside:", len(queue), "capacity:", cap(queue)) // inside: 3 capacity: 3
queue <- "tendon meatballs"
- The second number in
makeis the buffer capacity. A sender only waits when the buffer is full; a receiver waits when it is empty. - The first three sends go straight in even though nobody is receiving yet.
lengives how many are in now,capthe capacity. - The fourth send waits for a free place. There is no other goroutine here, so the result is the same:
fatal error: all goroutines are asleep - deadlock!withgoroutine 1 [chan send].
make(chan string) |
make(chan string, 3) |
|
|---|---|---|
| A send waits when | there is no receiver yet | the buffer is full (3 in it) |
| A receive waits when | there is no sender yet | the buffer is empty |
| Good for | a meeting point, a "taken" signal | dropping things off first, up to a limit |
close and range
The sender closes a channel with close when it has nothing more to send. The receiver can use range to take everything in it until the channel is closed:
func till(queue chan<- string) {
for _, menu := range []string{"tendon meatballs", "chicken noodles", "iced tea"} {
fmt.Println("till sends:", menu)
queue <- menu
}
close(queue)
}
func main() {
queue := make(chan string)
go till(queue)
for menu := range queue {
fmt.Println("kitchen cooks:", menu)
}
fmt.Println("queue empty, kitchen takes a break")
}
$ go run stall.go
till sends: tendon meatballs
till sends: chicken noodles
kitchen cooks: tendon meatballs
kitchen cooks: chicken noodles
till sends: iced tea
kitchen cooks: iced tea
queue empty, kitchen takes a break
queue chan<- stringin the parameter meanstillmay only send on that channel.close(queue)is called by the till after the last order.- The order of the
till sendsandkitchen cookslines can differ from run to run, because two goroutines print in turns. The order of the orders stays the same: tendon meatballs, chicken noodles, iced tea. for menu := range queuestops by itself once the channel is closed and empty. Withoutclose,rangewaits forever and ends in a deadlock.- Receiving from a closed, empty channel does not wait: you get the type's zero value. Use the two-value form to tell them apart:
m, ok := <-queuegivesm=""andok=false. Withfmt.Printf("%q %v\n", m, ok), it prints"" false.
📌 Channel direction in parameters
func till(queue chan<- string) means till may only send. <-chan string means it may only receive. The compiler refuses a breach: receiving from a chan<- string fails with invalid operation: cannot receive from send-only channel chan<- string queue (variable of type chan<- string). This makes each function's role clear from its signature.
⚠️ Deadlocks and panics around close
- Sending in main with no receiver. An unbuffered channel deadlocks at once. Make sure a goroutine receives, or use a buffer.
- Forgetting
closebeforerange. The receiver waits forever:goroutine 1 [chan receive]and a deadlock. - Sending on a closed channel. The program panics with
panic: send on closed channel. Closing twice panics too:panic: close of closed channel. The sender does the closing, once. - Treating close as required. A channel does not have to be closed. Close it only when the receiver needs to know "there is no more", for example for
range.
TL;DR: A channel sends values between goroutines: queue := make(chan string), send with queue <- "tendon meatballs", receive with m := <-queue. Unbuffered (make(chan T)): the sender waits until a receiver is ready. Buffered (make(chan T, 3)): the sender only waits when the buffer is full. When every goroutine is waiting on another, the program dies with fatal error: all goroutines are asleep - deadlock!. The sender closes a channel with close, range reads until the channel is closed, and receiving from a closed, empty channel gives the zero value with ok == false. Sending on a closed channel or closing twice panics.
⚡ Send and receive
Write:
queue := make(chan string)
go func() {
queue <- "tendon meatballs"
}()
order := <-queue
Meaning: The direction of the <- arrow gives the meaning: queue <- v sends, <-queue receives. main is held on the receive line until the goroutine sends.
⚡ Unbuffered: they have to meet
Guess first: queue := make(chan string), then main goes straight to queue <- "tendon meatballs" with no other goroutine. What happens?
A deadlock: fatal error: all goroutines are asleep - deadlock!. The sender waits for a receiver, and the only goroutine is main, the one waiting.
Meaning: With make(chan string, 3), a sender only waits when the buffer is full, that is when 3 are in it.
⚡ close and range
Write:
for menu := range queue {
fmt.Println("kitchen cooks:", menu)
}
Meaning: range reads until the channel is closed and empty. The sender closes it with close(queue), only once. Without close, range waits forever.