go · level 3 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A holds a few values before anyone waits.
make(chan string, 3) makes a buffered channel with a of 3: room for three values. A send drops its value in and carries on at once, unless the buffer is full; only then does it wait. A receive takes the oldest value, and waits only when the buffer is empty.
len(ch) tells you how many values are waiting and cap(ch) how many fit. Values come out in the order they went in, like a queue at the bakery.
If every goroutine is waiting and none can ever move, the program is stuck for good. That is a , and Go stops it with all goroutines are asleep - deadlock!. A bigger buffer can hide a design mistake, so count your sends and receives first.
package main
import "fmt"
func main() {
queue := make(chan string, 3)
queue <- "Ada"
queue <- "Grace"
fmt.Println(len(queue), "waiting, room for", cap(queue))
fmt.Println("Serving", <-queue)
fmt.Println(len(queue), "waiting")
} No goroutine is needed here, because both sends fit in the buffer.
guess first
Three tickets go in, one is thrown away. What prints?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
tickets := make(chan int, 4)
tickets <- 7
tickets <- 8
tickets <- 9
<-tickets
fmt.Println(<-tickets, len(tickets), cap(tickets))
}
your turn
Your turn. Take orders before the kitchen opens.
Choose a capacity big enough for two orders, then type two orders of your own. No goroutine will receive them until later.
output
press run to see what happens
fix it
The laundry piles up and stops. Can you fix it?
output
press run to see what happens
- It is a deadlock. Which send has nowhere to go?
- The buffer holds 2 values, and the third send waits for a receiver that only starts later.
- Give the channel room for all three:
make(chan string, 3).
nailed it
your channels have room to breathe. :D
make(chan T, n)gives a channel room for n values.- A send waits only when the buffer is full.
- Everyone waiting forever is a deadlock.
new words in your collection
- buffered channel
- capacity
- deadlock
This lesson isn’t saved. A free account remembers every lesson you finish.