Thuta Learning
Go
AdvancedProgrammingBeginner

Channels

GoLesson 2035 min

What you'll walk away with

  • Explain make(chan T) versus make(chan T, n) in terms of when operations block
  • Send, receive, and use v, ok := <-ch to tell whether a channel is closed
  • Follow the ownership rule: the sender closes, the receiver ranges
  • Use the direction types chan<- T and <-chan T in function signatures
  • Read the error all goroutines are asleep - deadlock! and find its cause

Explain it simply

Channels in plain language

A channel is a typed pipe between goroutines. One goroutine puts a value in with ch <- v and another takes it out with <-ch. A chan int carries only ints, so sending the wrong type is rejected by the compiler at once.

It works like passing a baton in a relay race. With an unbuffered channel the runner can hand over the baton only when the next runner's hand is out, and must stop and wait otherwise. A buffered channel is like a small table where batons can be left: while there is room, you put one down and keep running. The handover carries both the value and the signal 'I am done', which is what makes channels so useful.

Problem → Why → Solution

The problem: the program stops with a deadlock

Most people trying channels for the first time send a value and then immediately try to read it back. The code compiles, but as soon as it runs it crashes with fatal error: all goroutines are asleep - deadlock!. The message does not explain itself, so people start making random fixes such as adding a buffer or a sleep.

deadlock.go
package main

import "fmt"

func main() {
	results := make(chan int)
	results <- 42 // blocks forever: nobody is receiving yet
	fmt.Println(<-results)
}

Why this deadlocks

A send on an unbuffered channel blocks until a receiver actually arrives. This program has only one goroutine, and it is stuck on the send, so it never reaches the receive on the next line. The runtime notices that every goroutine is blocked and stops the program instead of hanging forever. The fix is to put the send and the receive in two different goroutines.

Core concept: a channel carries a value and synchronization together

On an unbuffered channel, made with make(chan T), the send and the receive wait for each other; the value changes hands only when both sides meet, and then both continue. That is why, once a receive completes, the receiver is guaranteed to see all the work the sender did before sending. A buffered channel, made with make(chan T, n), holds up to n values: a send blocks only when the buffer is full, and a receive blocks only when it is empty.

close(ch) announces 'no more values are coming'; it does not destroy the channel. After close, values still in the buffer can be read, and once they are gone a receive returns the zero value immediately. The form v, ok := <-ch reports ok == false to tell you that this zero value was never really sent. for v := range ch keeps reading until the channel is closed and drained, then leaves the loop.

OperationClosed channelnil channel
ch <- v (send)panicblocks forever
<-ch (receive)remaining values, then zero value with ok=falseblocks forever
close(ch)panic (closed twice)panic

That table leads to an ownership rule: only the sending side, the owner, closes a channel. If a receiver closes it, the sender's next send panics. Let the compiler enforce the rule with direction types: chan<- int can only be sent to, <-chan int can only be received from, and even closing a receive-only channel is a compile error. A plain chan int converts to either type automatically, so call sites need no extra code.

A channel is a pipe with one owner
  1. The owner makes the channel
  2. The owner sends with ch <- v
  3. Receivers read with <-ch or range
  4. The owner calls close(ch) when done
  5. range stops after close and drain

If you cannot say who receives a send, or who closes the channel a range is reading, you already have a deadlock or a goroutine leak.

General pattern

go
ch := make(chan T)      // unbuffered
buf := make(chan T, n)  // buffered, room for n values

ch <- value             // send
v := <-ch               // receive
v, ok := <-ch           // ok == false: closed and drained
close(ch)               // only the sender closes

for v := range ch { ... } // until close
func produce(out chan<- T) {} // send-only parameter
func consume(in <-chan T) {}  // receive-only parameter

The arrow points the way data flows: in ch <- v the value goes into the channel, and in <-ch it comes out. An arrow in a parameter type likewise states how that function is allowed to use the channel.

Worked example: one message between two goroutines

This is the smallest useful shape of a channel. An anonymous goroutine sends "ping" and the main goroutine receives it. There is no WaitGroup, yet main still waits for the goroutine, because the unbuffered receive blocks until the value arrives. That is why the output is always ping.

go
package main

import "fmt"

func main() {
    messages := make(chan string)

    go func() {
        messages <- "ping"
    }()

    msg := <-messages
    fmt.Println(msg)
}

Code breakdown

  1. Make an unbuffered channelmessages := make(chan string)

    An unbuffered channel that carries strings. The zero value of a channel is nil, so declaring var messages chan string without make would make every send and receive block forever.

  2. Send from another goroutinemessages <- "ping"

    This send blocks until main receives. Because it lives in its own goroutine it does not block main, which is exactly the difference from the deadlock in the problem section.

  3. Receive and waitmsg := <-messages

    main pauses here until a value arrives. It receives synchronization along with the value, so main sees everything the goroutine did before its send.

  4. Anonymous goroutinego func() {

    A function literal is started as a goroutine on the spot. As a closure it can use messages directly, without receiving it as an argument.

You should see
ping

close, range and buffered channels

When more than one value is sent, the receiver needs to know when to stop. Below, produce sends three values and then closes the channel; the range in main stops when it sees that close. The second half reads from the closed channel and shows len and cap of a buffered channel.

range.go
package main

import "fmt"

func produce(n int, out chan<- int) {
	for i := 1; i <= n; i++ {
		out <- i * 10 // blocks until main is ready to receive
	}
	close(out) // the sender closes: "no more values are coming"
}

func main() {
	nums := make(chan int) // unbuffered
	go produce(3, nums)

	sum := 0
	for v := range nums { // ends after close and the last value
		fmt.Println("received", v)
		sum += v
	}
	fmt.Println("sum:", sum)

	v, ok := <-nums // a closed channel gives the zero value and ok == false
	fmt.Println("after close:", v, ok)

	queue := make(chan string, 2) // buffered: room for 2 values
	queue <- "a"
	queue <- "b" // no receiver yet, and still no block
	fmt.Println("len/cap:", len(queue), cap(queue))
	fmt.Println(<-queue, <-queue)
}

The output is received 10, 20 and 30, then sum: 60, after close: 0 false, len/cap: 2 2 and a b. The values arrive in order because there is a single sender and a channel is FIFO. queue accepts two sends with no receiver because it has two buffer slots; a third send would block.

When to use a buffer

A buffer loosens synchronization, so it should not be used to hide a deadlock. Use one to smooth out short bursts where producer and consumer run at different speeds, or to let a sender finish even if the receiver will read the result only once.

ChannelGood fit
make(chan T)every handoff should be confirmed; the default choice
make(chan T, 1)one result, and the sender should exit at once
make(chan T, n)a queue that absorbs bursts; choose n by measuring
make(chan struct{})a done signal that carries no data

In real projects

Channels in real projects

The Go proverb 'do not communicate by sharing memory; share memory by communicating' is about channels. Ownership of a piece of data moves from one goroutine to the next, so only one of them owns it at any moment.

  • Log shippers: request handlers send log lines into a buffered channel and a single goroutine batches them to a file or a remote service, so the file needs no lock.
  • Graceful shutdown: signal.Notify delivers OS signals to a channel, and main blocks on <-sigCh to stop the server when Ctrl+C arrives.
  • Standard library: time.After, time.Ticker.C and context.Context's Done() all return channels, so understanding channels also explains the timer and cancellation APIs.

Common mistakes

Common mistakes with channels

Sending unbuffered with no receiver

Writing the send and the receive one after another in the same goroutine, as in the problem section, deadlocks. Adding a buffer of 1 makes that example work, but it breaks again the day a second send arrives. The real fix is to run the sender or the receiver in a separate goroutine.

Closing from the receiver, or closing twice

When a consumer calls close(ch) because it has 'finished reading', the producer's next send panics with send on closed channel. With several producers, none of them should close; a single goroutine that waits for all of them with a WaitGroup closes the channel once.

Forgetting close, so range never ends

If the producer sends everything but never closes, for v := range ch waits forever for the next value. In main that ends in the deadlock error; in any other goroutine it is a silent leak. Writing defer close(out) at the top of the producer prevents this mistake.

Mini challenge

Mini challenge: countdown and logger

Write a small program with two channels. countdown(from) returns a receive-only channel; a goroutine sends from down to 1 and then closes it. logger reads a lines channel until it is closed, numbering and printing each line, then closes a done channel to signal main.

  • countdown returns <-chan int and closes its channel with defer close
  • logger's parameters are <-chan string and chan<- struct{}
  • main owns lines, so main is the one that closes lines
  • main waits for logger with <-done, never with a sleep
countdown.go
package main

import "fmt"

// countdown sends from, from-1, ... 1 and then closes the channel.
func countdown(from int) <-chan int {
	// TODO: make the channel, start a goroutine that sends and closes it
	return nil
}

// logger prints every line it receives, then signals done.
func logger(lines <-chan string, done chan<- struct{}) {
	// TODO: range over lines, number each one, print "log N: text"
	// TODO: print how many lines were seen, then close(done)
}

func main() {
	// TODO: make lines (buffered is fine) and done
	// TODO: start logger, send "T-minus N" for each countdown value,
	//       send "liftoff", close lines, wait on done
	fmt.Println("todo")
}

Expected: Every run prints log 1: T-minus 3, log 2: T-minus 2, log 3: T-minus 1, log 4: liftoff and then logger saw 4 lines, always in that order.

Show hint

Inside countdown, make out := make(chan int), start the goroutine and return out right away; the goroutine keeps sending in the background. If main does not wait on <-done, logger's last lines may never print.

Show solution
countdown.go
package main

import "fmt"

// countdown returns a receive-only channel; the goroutine that owns the
// channel sends every value and then closes it.
func countdown(from int) <-chan int {
	out := make(chan int)
	go func() {
		defer close(out)
		for i := from; i >= 1; i-- {
			out <- i
		}
	}()
	return out
}

// logger receives lines until the channel closes, then signals done.
func logger(lines <-chan string, done chan<- struct{}) {
	n := 0
	for line := range lines {
		n++
		fmt.Printf("log %d: %s\n", n, line)
	}
	fmt.Println("logger saw", n, "lines")
	close(done)
}

func main() {
	lines := make(chan string, 4)
	done := make(chan struct{})
	go logger(lines, done)

	for n := range countdown(3) {
		lines <- fmt.Sprint("T-minus ", n)
	}
	lines <- "liftoff"
	close(lines) // main owns lines, so main closes it
	<-done       // wait until logger has printed everything
}

Quick quiz 1 / 3

What does ch := make(chan int, 2); ch <- 1; ch <- 2; close(ch); for v := range ch { fmt.Print(v, " ") } print?

Quick quiz 2 / 3

names is a closed chan string with no values left. After v, ok := <-names, what are v and ok?

Quick quiz 3 / 3

Three producer goroutines send to one results channel. Who should close results?

What to remember

  • A channel is a typed pipe that hands over a value and synchronization together.
  • Unbuffered sends and receives wait for each other; buffered ones block only when full or empty.
  • Only the sender (the owner) closes; receivers detect it with range or v, ok := <-ch.
  • chan<- T and <-chan T let the compiler enforce how a function may use a channel.
  • When every goroutine is blocked the runtime stops with a deadlock error; a buffer is not the fix.

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Channels | Thuta Learning