Skip to content
Tutorials Center
My learning

Topics

Lesson 66 of 147 ยท Concurrency

Channels

Learn Go channels - make(chan T), blocking sends and receives, unbuffered rendezvous, close and range, receiving from closed channels, nil channels, directions and deadlocks.

Goroutines let you run code at the same time, but they need a safe way to hand data to each other. Sharing variables and guarding them with locks works, yet it is easy to get wrong. Go's preferred style is summed up in a well-known proverb: do not communicate by sharing memory; share memory by communicating. The tool for that is the channel.

A channel is a typed pipe. One goroutine sends a value into it, another receives the value out of it. The send and receive also synchronize the two goroutines, so a channel both moves data and coordinates timing. This lesson covers creating channels, the blocking rules, closing and ranging, the special behavior of closed and nil channels, channel directions, deadlocks and the ownership rules that keep channel code simple. If you have not yet met goroutines, start with Goroutines.

Creating a channel

A channel has an element type. chan int carries int values, chan string carries strings, and chan struct{} carries nothing at all (useful for signals). The zero value of a channel is nil; you create a usable one with make:

Go
ch := make(chan int)      // an unbuffered channel of int
done := make(chan struct{})
lines := make(chan string, 10) // buffered, covered in the next lesson

Two operators use the arrow <-, which always points in the direction the data flows:

Go
ch <- 42      // send: put 42 into the channel
v := <-ch     // receive: take a value out and store it in v
<-ch          // receive and discard the value
Go A first send and receive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The program prints received: ping. main reaches the receive first, and waits there until the goroutine sends. No WaitGroup and no Sleep is needed: the receive itself is the wait.

Unbuffered channels are rendezvous points

A channel made with make(chan T) has no storage, so it is unbuffered. A send on it blocks until another goroutine is ready to receive, and a receive blocks until another goroutine is ready to send. Both goroutines meet at the channel, exchange the value, and then both continue. Because of this meeting, everything the sender did before the send is guaranteed to be visible to the receiver after the receive.

Go Send and receive wait for each other

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The two lines worker: waiting for a number and main: about to send can appear in either order, because both goroutines run independently up to the channel. After the send, worker: got 7 always comes before main: finished, since main waits on done. Closing done is the standard way to signal "I am finished" without sending any data.

Using a channel to return a result

Since go f() throws the return value away, a common pattern is to send the result over a channel instead:

Go Collecting results from goroutines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

total: 36 is printed no matter which half finishes first, because addition does not care about order. (Which of a and b holds which half is not defined, and that is why this works only for operations where order is irrelevant.) The parameter type chan<- int is a channel direction, explained below.

Closing a channel and ranging over it

How does a receiver know that a sender has no more values? The sender calls the built-in close(ch). Closing says "nothing will ever be sent again". A for ... range loop over a channel receives values until the channel is closed and empty:

Go range over a channel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The loop prints got 10 through got 50 in order and then ends by itself. Without the close, the loop would wait forever for a sixth value and the program would die with a deadlock. Note that the function returns a receive-only channel (<-chan int), which hands the consumer exactly the permissions it needs.

You do not have to close every channel. Closing is only necessary when the receiver must be told that the stream is over, for example in a range loop. A channel that is no longer used is garbage collected like any other value.

The rules of close

  • Only the sender should close, never the receiver. A receiver cannot know whether another sender is still active.
  • Sending on a closed channel panics (send on closed channel).
  • Closing a closed channel panics (close of closed channel), and closing a nil channel panics too.
  • Receiving from a closed channel never blocks and never panics.

Receiving from a closed channel

Once a channel is closed and its remaining values have been delivered, every receive returns immediately with the zero value of the element type. That makes it impossible to tell a real 0 from "closed" by the value alone, so a receive has a second form that also reports whether the value is genuine, the comma-ok idiom you know from maps:

Go Comma-ok receive on a closed channel

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The output is:

TEXT
v=5 ok=true
v=0 ok=true
v=0 ok=false
v=0 ok=false

The first two lines are real values (the second one really is 0). After that the channel is closed and empty, so ok is false and v is the zero value. A range loop uses exactly this check to know when to stop.

A closed channel is also a handy broadcast. Because every receiver gets an immediate result, closing a chan struct{} wakes all goroutines waiting on it at once:

Go Closing a channel wakes every waiter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The goroutines are released together, and the result [ann bob cy] is sorted so that it does not depend on scheduling. A single send would release only one waiter; close releases them all.

Channel directions

A bidirectional chan T can be converted implicitly to a one-way channel, and the compiler then enforces the direction:

  • chan<- T is send-only: you can send to it and close it, but not receive.
  • <-chan T is receive-only: you can receive from it, but not send or close.
Go
func producer(out chan<- int) { out <- 1 }   // can only send
func consumer(in <-chan int)  { fmt.Println(<-in) } // can only receive

The usual uses are: a function that produces values takes or returns <-chan T so callers can only read; a function that consumes takes <-chan T; a worker that reports results takes chan<- T. Returning <-chan T from a constructor function is the standard way to hand out a stream that only the creator may write to or close. Directions document intent and turn mistakes into compile errors. You cannot convert a one-way channel back to a bidirectional one.

Go Sending on a receive-only channel (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The compiler rejects the program before it runs:

TEXT
./main.go:9:2: invalid operation: cannot send to receive-only channel <-chan int recvOnly (variable of type <-chan int)

nil channels

A channel variable that was declared but never created with make is nil. Sending to or receiving from a nil channel blocks forever, and closing one panics:

Go
var ch chan int // nil
ch <- 1         // blocks forever
<-ch            // blocks forever
close(ch)       // panic: close of nil channel

That is usually a bug (a forgotten make), but it is also a deliberate tool: inside a select statement, a nil channel is never ready, so setting a channel variable to nil switches that case off. The next lesson uses this trick.

Deadlocks

If every goroutine in the program is blocked and none can ever wake up, the Go runtime notices and stops the program with a fatal error. This is a deadlock. The simplest way to cause one is to send on an unbuffered channel when nobody receives:

Go A send nobody receives (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The runtime prints:

TEXT
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
	main.go:7 +0x...

The bracketed text chan send tells you what the goroutine is waiting for, and the line number points at the blocked statement. The fix is to run the sender or the receiver in another goroutine, or to use a buffer.

The runtime can detect a deadlock only when all goroutines are stuck. If a single goroutine still runs (a ticker, an HTTP server, a loop), a stuck goroutine just waits forever and nothing is reported. That is exactly how goroutine leaks go unnoticed.

Who closes? Channel ownership

Channels are easy to misuse when it is unclear who is responsible for them. A simple convention keeps the code readable: the goroutine that creates a channel (or the only one that sends on it) owns it. The owner:

  1. creates the channel,
  2. performs all the writes,
  3. closes it when finished,
  4. exposes it to others as receive-only.

Consumers only read, and they never close. The produce function earlier follows this exactly: it makes the channel, sends in a goroutine, defers the close and returns <-chan int.

When several goroutines send on the same channel, none of them should close it, because the others would then panic. Use a WaitGroup and let one extra goroutine close the channel after all senders are done:

Go Many senders, one closer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

All three greetings arrive, in an unpredictable order, so the program collects and sorts them before printing. The small closer goroutine is the idiom to remember: wait for the senders, then close.

Channels hold values, not references to goroutines

Sending a value on a channel copies it, like any assignment. Sending a pointer, a slice or a map copies only the small header, so both goroutines then share the underlying data. When you send a pointer, treat it as a hand-over: after the send, the sender should no longer touch the data, otherwise you have created a data race that the channel does not protect you from.

Channels are also not free. They are great for passing ownership of data, distributing work and signalling events. For simply protecting a counter or a cache, a mutex from the sync package is shorter and faster. Choose the tool that matches the problem.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a send on an unbuffered channel, ch <- v, do when no goroutine is receiving?

    An unbuffered channel has no storage. The sender waits until a receiver is ready, and then they exchange the value.
  2. 2. What is printed?

    ch := make(chan int, 1); ch <- 8; close(ch); a, ok1 := <-ch; b, ok2 := <-ch; fmt.Println(a, ok1, b, ok2)

    A closed channel still delivers its remaining buffered values with ok set to true. After that, receives return the zero value with ok false and never block or panic.
  3. 3. Which statement about closing channels is correct?

    Sending on a closed channel panics. Only the sender should close, and closing is needed only to tell receivers that no more values come.
  4. 4. What is the type <-chan int?

    The arrow on the left of chan means the data comes out: it is a receive-only channel. chan<- int is the send-only type.
  5. 5. What happens when main does var ch chan int; <-ch and no other goroutine exists?

    Receiving from a nil channel blocks forever. With no other goroutine left to run, the runtime detects the deadlock and stops the program.

Summary

  • A channel is a typed, goroutine-safe pipe: make(chan T), ch <- v to send, v := <-ch to receive.
  • Unbuffered channels make sender and receiver meet, so communication also synchronizes.
  • close(ch) signals that no more values come; for v := range ch ends when the channel is closed and drained.
  • Receiving from a closed channel returns the zero value immediately; use v, ok := <-ch to tell the difference.
  • Sending on or closing a closed channel panics, so only the owner (the sender) closes; with several senders, close after a WaitGroup finishes.
  • chan<- T is send-only and <-chan T is receive-only; use them in signatures to document and enforce intent.
  • Nil channels block forever, and a program where every goroutine is blocked stops with a deadlock error.

Next: Buffered Channels and select adds queues, timeouts and waiting on many channels at once.