Learn Channel in Go

A channel sends values between goroutines: queue := make(chan string), send with queue <- "tendon meatballs", receive with m := <-queue. Unbuffered (make(chan…

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

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"
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

📌 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

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.

What you will learn