SyntaxPilot
Courses/Go Programming/Lesson 48
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Go Programming · Lesson 48 of 89

Channels: semantics in depth

channel axioms (send to nil blocks, receive from nil blocks, send to closed panics, receive from closed returns zero value, close of closed panics)channel ownershipwho should closedeadlock and "all goroutines are asleep"signalling with chan struct{}closing as broadcasthchan internals (buffer, sendq, recvq)

These are the notes for Go episode 48. Raju's kitchen now has two cooks sending through one hatch, and each closes it when done: the program crashes with panic: send on closed channel, and two closes give panic: close of closed channel. You invent channel ownership: senders only send, one owner closes exactly once. Then the cashier who expects 5 bills learns that a closed channel hands out zero values instantly, a struct whose channel nobody made shows that nil channels block forever, three mandi suppliers show a goroutine leak that Go cannot detect, the kitchen bell becomes chan struct{}, sending "go home" once wakes only one of three boys until close is used as a broadcast, and finally you look inside a real channel: the runtime's hchan with its circular buffer, sendx/recvx, and the sendq/recvq wait queues.

All outputs and errors here are from real runs (Go 1.24.7, linux/amd64, a machine with 2 CPUs). Goroutine numbers, addresses and the order of some lines can change between runs.

Facts and sources

  • The Go Programming Language Specification, Send statements: "A send on a closed channel proceeds by causing a run-time panic. A send on a nil channel blocks forever."
  • Same, Receive operator: "Receiving from a nil channel blocks forever. A receive operation on a closed channel can always proceed immediately, yielding the element type's zero value after any previously sent values have been received." And for v, ok := <-ch: "The value of ok is true if the value received was delivered by a successful send operation to the channel, or false if it is a zero value generated because the channel is closed and empty."
  • Same, Close: "Sending to or closing a closed channel causes a run-time panic. Closing the nil channel also causes a run-time panic." Channel types: "A nil channel is never ready for communication."
  • Channel Axioms, Dave Cheney, 19 March 2014: "A send to a nil channel blocks forever", "A receive from a nil channel blocks forever", "A send to a closed channel panics", "A receive from a closed channel returns the zero value immediately".
  • runtime/chan.go: hchan has qcount ("total data in the queue"), dataqsiz ("size of the circular queue"), buf ("points to an array of dataqsiz elements"), sendx ("send index"), recvx ("receive index"), recvq ("list of recv waiters"), sendq ("list of send waiters") and lock ("protects all fields in hchan"). The panics are "close of nil channel", "close of closed channel" and "send on closed channel". In Go 1.24.7's source the fields also include elemsize, synctest, closed, timer and elemtype, in this order: qcount, dataqsiz, buf, elemsize, synctest, closed, timer, elemtype, sendx, recvx, recvq, sendq, lock.

The problem: two cooks, one hatch

In Raju's kitchen In Go
Raju and Asha cook two sender goroutines
one hatch to the counter one channel
each hangs the "closed" sign when done each calls close(hatch)
Asha pushes a dish into a closed hatch send on a closed channel
package main

import (
    "fmt"
    "time"
)

func cook(name string, dishes []string, gap time.Duration, hatch chan string) {
    for _, d := range dishes {
        time.Sleep(gap) // cooking
        hatch <- name + ": " + d
    }
    close(hatch) // "I'm done, close the hatch"
}

func main() {
    hatch := make(chan string)
    go cook("Raju", []string{"dosa"}, 50*time.Millisecond, hatch)
    go cook("Asha", []string{"idli", "vada"}, 120*time.Millisecond, hatch)
    for d := range hatch {
        fmt.Println("delivering", d)
    }
    fmt.Println("all delivered?")
    time.Sleep(300 * time.Millisecond)
}

Real output:

delivering Raju: dosa
all delivered?
panic: send on closed channel

goroutine 7 [running]:
main.cook(...)
    main.go:11
created by main.main in goroutine 1
    main.go:19 +0xa5
exit status 2

What happened: Raju (one dish, 50 ms) finished first and closed the hatch. The range loop ended at once ("all delivered?" printed, with Asha's dishes never delivered), and when Asha sent her next dish, the program crashed. A panic (episode 26) is Go stopping the program because something happened that must never happen; the message and the stack trace (main.cook(...) main.go:11) tell you where.

Rule: sending on a closed channel panics. Go has no "is this channel closed?" function on purpose: the answer could change the instant after you check.

Closing twice

package main

import "fmt"

func main() {
    hatch := make(chan string, 1)
    hatch <- "dosa"
    close(hatch) // Raju closes the hatch
    fmt.Println("Raju closed it")
    close(hatch) // Asha closes it too
    fmt.Println("Asha closed it")
}

Real output:

Raju closed it
panic: close of closed channel

goroutine 1 [running]:
main.main()
    main.go:10 +0x87
exit status 2

Rule: closing a channel that is already closed panics. Both bugs have one cause: nobody owned the hatch.

Who should close: channel ownership

In Raju's kitchen In Go
one keeper owns the hatch the owner goroutine makes the channel and closes it
cooks only push dishes senders get chan<- T, send, never close
the keeper waits for every cook, then hangs the sign once sync.WaitGroup (episode 45), then one close

Ownership means one goroutine is responsible for a channel's life: it makes it and, if receivers need to know the end, closes it once.

package main

import (
    "fmt"
    "sync"
    "time"
)

// cooks only send: they never close
func cook(name string, dishes []string, gap time.Duration, hatch chan<- string, wg *sync.WaitGroup) {
    defer wg.Done()
    for _, d := range dishes {
        time.Sleep(gap)
        hatch <- name + ": " + d
    }
}

func main() {
    hatch := make(chan string) // main owns the hatch
    var wg sync.WaitGroup
    wg.Add(2)
    go cook("Raju", []string{"dosa"}, 50*time.Millisecond, hatch, &wg)
    go cook("Asha", []string{"idli", "vada"}, 120*time.Millisecond, hatch, &wg)
    go func() {
        wg.Wait()    // when every cook is done...
        close(hatch) // ...the owner closes, exactly once
    }()
    for d := range hatch {
        fmt.Println("delivering", d)
    }
    fmt.Println("all delivered")
}

Real output (the order of the first two lines can swap):

delivering Raju: dosa
delivering Asha: idli
delivering Asha: vada
all delivered

Why the closer runs in its own goroutine: main must be free to range over the hatch while the cooks are still sending. If main called wg.Wait() itself before the loop, the cooks would block on the unbuffered sends (nobody receiving) and wg.Wait() would never return: a deadlock.

The rules

  1. The sender side closes, never the receiver (a receiver that closes makes the next send panic).
  2. One sender: it closes when it's done.
  3. Many senders: an owner waits for all of them (WaitGroup), then closes once.
  4. Closing is a message to receivers: "no more values are coming".
  5. You don't have to close a channel to free it: when no goroutine can reach it, the garbage collector frees it. Close only when a receiver needs to know.

Receiving from a closed channel: instant zero values

At Raju's cash counter In Go
the cashier expects 5 bills, 2 came, then the shift ended 2 values sent, then close
every grab finds an empty tray, written down as 0 rupees a receive returns the zero value at once
look at the closed sign before counting v, ok := <-ch
package main

import "fmt"

func main() {
    bills := make(chan int, 5)
    bills <- 120
    bills <- 80
    close(bills) // only 2 bills today

    total := 0
    for i := 1; i <= 5; i++ { // the cashier expects 5 bills
        b := <-bills
        total += b
        fmt.Println("bill", i, "=", b)
    }
    fmt.Println("total:", total, "from 5 bills")
}

Real output:

bill 1 = 120
bill 2 = 80
bill 3 = 0
bill 4 = 0
bill 5 = 0
total: 200 from 5 bills

No crash, no hang: a silently wrong report. A receive on a closed channel never blocks; once buffered values are gone it returns the zero value of the element type (0 for int, "" for string, nil for pointers) immediately, forever.

The fix, with the comma-ok receive (episode 47):

package main

import "fmt"

func main() {
    bills := make(chan int, 5)
    bills <- 120
    bills <- 80
    close(bills) // only 2 bills today

    total, count := 0, 0
    for i := 1; i <= 5; i++ {
        b, ok := <-bills
        if !ok { // closed and empty: no more bills
            break
        }
        total += b
        count++
        fmt.Println("bill", i, "=", b)
    }
    fmt.Println("total:", total, "from", count, "bills")
}

Real output:

bill 1 = 120
bill 2 = 80
total: 200 from 2 bills

A plain receive cannot tell a real 0 (say, a free sample bill) from "closed". Use v, ok := <-ch or for v := range ch whenever a channel can be closed.

nil channels

In Raju's kitchen In Go
a hatch painted on the wall a nil channel: var ch chan T, never made
push a dish in, or wait for one send or receive blocks forever
hang a closed sign on a painting close(nil) panics

The zero value of a channel type is nil. Declaring a variable or a struct field of channel type without make leaves it nil.

package main

import "fmt"

type Kitchen struct {
    hatch chan string
}

func main() {
    var k Kitchen // forgot make: k.hatch is nil
    fmt.Println("hatch is nil:", k.hatch == nil)
    go func() {
        k.hatch <- "dosa" // the cook sends
    }()
    fmt.Println("got", <-k.hatch) // the boy receives
}

Real output:

hatch is nil: true
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive (nil chan)]:
main.main()
    main.go:15 +0x9a

goroutine 18 [chan send (nil chan)]:
main.main.func1()
    main.go:13 +0x1e
created by main.main in goroutine 1
    main.go:12 +0x88
exit status 2

The runtime even says (nil chan) in the goroutine states. Fix: k := Kitchen{hatch: make(chan string)}.

package main

import "fmt"

func main() {
    var hatch chan string // nil: never made
    fmt.Println("closing a nil channel...")
    close(hatch)
}

Real output:

closing a nil channel...
panic: close of nil channel

goroutine 1 [running]:
main.main()
    main.go:8 +0x4d
exit status 2

Why would "blocks forever" ever be useful? In select (episode 49), setting a channel variable to nil switches its case off.

The channel axioms

An axiom is a basic rule everything else is built on.

Operation nil channel open channel closed channel
send ch <- v blocks forever proceeds when a receiver / buffer slot is ready panic: send on closed channel
receive <-ch blocks forever proceeds when a value is ready buffered values first, then zero value at once (ok == false)
close(ch) panic: close of nil channel closes it panic: close of closed channel
len(ch), cap(ch) 0, 0 values waiting, buffer size values still buffered, buffer size

The first four rows of the send/receive behaviour are Dave Cheney's four axioms (2014); the close rules come from the specification.

Deadlocks vs goroutine leaks

A deadlock is a state where goroutines wait for each other forever. Go's runtime reports fatal error: all goroutines are asleep - deadlock! only when every goroutine is blocked, so nothing could ever happen again. If even one goroutine (often main) is still running or sleeping, the runtime can't know the others are stuck, and says nothing.

Raju's phone calls In Go
calls 3 mandis for today's onion price 3 goroutines
takes the first answer, hangs up one receive
two suppliers wait on the line forever goroutine leak
no alarm rings: the shop is open no deadlock error
package main

import (
    "fmt"
    "runtime"
    "time"
)

// a supplier answers with today's onion price
func ask(supplier string, delay time.Duration, answer chan string) {
    time.Sleep(delay)
    answer <- supplier // waits until someone receives
}

func main() {
    answer := make(chan string) // unbuffered
    go ask("Mandi A", 30*time.Millisecond, answer)
    go ask("Mandi B", 10*time.Millisecond, answer)
    go ask("Mandi C", 20*time.Millisecond, answer)
    fmt.Println("first answer:", <-answer)

    time.Sleep(100 * time.Millisecond)
    fmt.Println("goroutines alive:", runtime.NumGoroutine())
}

Real output:

first answer: Mandi B
goroutines alive: 3

runtime.NumGoroutine() returns how many goroutines exist right now, main included. A goroutine leak is a goroutine that can never finish: it holds its stack and everything it references until the program exits. In a server that does this on every request, memory grows without limit.

Fix 1: a slot for every sender, so late senders finish:

package main

import (
    "fmt"
    "runtime"
    "time"
)

// a supplier answers with today's onion price
func ask(supplier string, delay time.Duration, answer chan string) {
    time.Sleep(delay)
    answer <- supplier // waits until someone receives
}

func main() {
    answer := make(chan string, 3) // a slot for every supplier
    go ask("Mandi A", 30*time.Millisecond, answer)
    go ask("Mandi B", 10*time.Millisecond, answer)
    go ask("Mandi C", 20*time.Millisecond, answer)
    fmt.Println("first answer:", <-answer)

    time.Sleep(100 * time.Millisecond)
    fmt.Println("goroutines alive:", runtime.NumGoroutine())
}

Real output:

first answer: Mandi B
goroutines alive: 1

The unread values are garbage collected with the channel. Fix 2 (previewing select from episode 49): each sender also listens for a "stop" broadcast:

package main

import (
    "fmt"
    "runtime"
    "time"
)

func ask(supplier string, delay time.Duration, answer chan<- string, done <-chan struct{}) {
    time.Sleep(delay)
    select { // previewing next episode: send, or give up when told to stop
    case answer <- supplier:
    case <-done:
    }
}

func main() {
    answer := make(chan string) // still unbuffered
    done := make(chan struct{})
    go ask("Mandi A", 30*time.Millisecond, answer, done)
    go ask("Mandi B", 10*time.Millisecond, answer, done)
    go ask("Mandi C", 20*time.Millisecond, answer, done)
    fmt.Println("first answer:", <-answer)
    close(done) // broadcast: everyone else can stop
    time.Sleep(100 * time.Millisecond)
    fmt.Println("goroutines alive:", runtime.NumGoroutine())
}

Real output:

first answer: Mandi B
goroutines alive: 1

Always ask, for every goroutine you start: how does it end?

Signals: chan struct{}

In Raju's kitchen In Go
a bell: "ding" means ready chan struct{}: a signal channel
an empty envelope weighs nothing struct{}{}: the empty struct value, 0 bytes
a yes/no slip invites "what does no mean?" chan bool carries a value nobody reads

struct{} is a struct type with no fields; struct{}{} is its only value. unsafe.Sizeof reports how many bytes a value occupies.

package main

import (
    "fmt"
    "time"
    "unsafe"
)

func main() {
    fmt.Println("size of a bool:    ", unsafe.Sizeof(true))
    fmt.Println("size of a struct{}:", unsafe.Sizeof(struct{}{}))

    ready := make(chan struct{}) // carries no data, only "now"
    go func() {
        fmt.Println("cook: lighting the stove...")
        time.Sleep(100 * time.Millisecond)
        ready <- struct{}{} // the signal: an empty struct value
    }()
    <-ready // wait for the signal
    fmt.Println("boy: kitchen is ready, start taking orders")
}

Real output:

size of a bool:     1
size of a struct{}: 0
cook: lighting the stove...
boy: kitchen is ready, start taking orders

The signal carries an ordering ("the stove is lit before orders start"), not data. Common names: done, ready, quit, stop.

close as a broadcast

One value is received by exactly one receiver:

package main

import (
    "fmt"
    "sync"
)

func boy(id int, home <-chan struct{}, wg *sync.WaitGroup) {
    defer wg.Done()
    <-home // wait for "go home"
    fmt.Println("boy", id, "going home")
}

func main() {
    home := make(chan struct{})
    var wg sync.WaitGroup
    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go boy(i, home, &wg)
    }
    home <- struct{}{} // Raju says "go home"... once
    wg.Wait()
    fmt.Println("shop closed")
}

Real output:

boy 3 going home
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [sync.WaitGroup.Wait]:
sync.runtime_SemacquireWaitGroup(0xc00010af18?)
sync.(*WaitGroup).Wait(0x40afe8?)
main.main()
    main.go:22 +0xe5

goroutine 18 [chan receive]:
main.boy(0x1, 0x0?, 0x0?)
    main.go:10 +0x50
created by main.main in goroutine 1
    main.go:19 +0x4f

goroutine 19 [chan receive]:
main.boy(0x2, 0x0?, 0x0?)
    main.go:10 +0x50
created by main.main in goroutine 1
    main.go:19 +0x4f
exit status 2

Replace the send with close(home): a receive on a closed channel proceeds at once for every receiver, now and in the future, so close is a broadcast.

package main

import (
    "fmt"
    "sync"
)

func boy(id int, home <-chan struct{}, wg *sync.WaitGroup) {
    defer wg.Done()
    <-home // wait for "go home"
    fmt.Println("boy", id, "going home")
}

func main() {
    home := make(chan struct{})
    var wg sync.WaitGroup
    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go boy(i, home, &wg)
    }
    close(home) // Raju closes: every waiting receiver wakes
    wg.Wait()
    fmt.Println("shop closed")
}

Real output (the order of the boys changes from run to run):

boy 3 going home
boy 1 going home
boy 2 going home
shop closed
one send ch <- struct{}{} close(ch)
wakes one receiver wakes every receiver
you must know how many are waiting works for any number, even 0
can be repeated only once (closing again panics)

This is how cancellation works in Go; the context package (episode 51) is built on a Done() channel that is closed.

Inside a channel: hchan

make(chan T, n) asks the runtime (the part of Go linked into every program that manages goroutines, memory and channels) for an hchan, the channel header. Your channel variable is just a pointer to it, which is why copying a channel value shares the same channel.

Behind the hatch hchan field Meaning
a round shelf with numbered slots buf, dataqsiz a circular buffer (a fixed array used round and round) and its size (cap)
how many dishes are on it qcount values waiting (len)
next free slot / next dish to take sendx, recvx indexes into buf, wrapping round to 0
the closed sign closed set by close
a queue of cooks holding plates sendq goroutines blocked sending
a queue of boys with empty hands recvq goroutines blocked receiving
one lock on the hatch door lock a runtime mutex guarding every field

A goroutine that can't proceed is wrapped in a sudog (the runtime's record of a goroutine waiting on a channel), added to sendq or recvq, and put to sleep: no CPU used. When the other side arrives, the runtime takes the first sudog, copies the value (directly from sender to receiver on an unbuffered channel) and wakes that goroutine.

For learning only — this reads the runtime's private memory layout with unsafe (the package that lets a program step around Go's type safety). It breaks whenever the layout changes (Go 1.23 added timer, Go 1.24 synctest). Never do this in real code.

package main

import (
    "fmt"
    "time"
    "unsafe"
)

type hchan struct { // copied from runtime/chan.go (Go 1.24), for learning only
    qcount, dataqsiz uint       // values in the buffer, buffer size
    _                [4]uintptr // buf, elemsize, closed, timer, elemtype
    sendx, recvx     uint       // next slot to send into / receive from
    recvq, sendq     [2]uintptr // goroutines waiting to receive / send
}

func peek(label string, ch chan string) {
    h := *(**hchan)(unsafe.Pointer(&ch)) // a channel value points to an hchan
    fmt.Printf("%-8s qcount=%d dataqsiz=%d sendx=%d recvx=%d waiting senders=%v\n",
        label, h.qcount, h.dataqsiz, h.sendx, h.recvx, h.sendq[0] != 0)
}

func main() {
    shelf := make(chan string, 3)
    shelf <- "dosa"
    shelf <- "idli"
    peek("2 sent", shelf)
    fmt.Println("took", <-shelf)
    shelf <- "vada"
    shelf <- "poha" // wraps round to slot 0
    peek("full", shelf)
    go func() { shelf <- "upma" }() // no room: this sender waits
    time.Sleep(50 * time.Millisecond)
    peek("blocked", shelf)
}

Real output:

2 sent   qcount=2 dataqsiz=3 sendx=2 recvx=0 waiting senders=false
took dosa
full     qcount=3 dataqsiz=3 sendx=1 recvx=1 waiting senders=false
blocked  qcount=3 dataqsiz=3 sendx=1 recvx=1 waiting senders=true

Reading it: after two sends, qcount=2, sendx=2. Taking dosa from slot 0 moves recvx to 1. Two more sends fill the buffer and sendx wraps round to 1. A fifth sender has no room, so it waits in sendq (waiting senders=true).

Takeaways: every channel operation is a lock, some bookkeeping and maybe a sleep: cheap, not free. A mutex is often faster for simply guarding data; use channels to pass ownership of data and to signal events.

Mini project: closing time

Three cooks send four orders each into one channel (send-only, never closing); an owner closes it once after a WaitGroup; two delivery boys range over it and signal on done; main prints the total and proves there is no leak.

package main

import (
    "fmt"
    "runtime"
    "sync"
    "time"
)

func cook(name string, orders chan<- string, wg *sync.WaitGroup) {
    defer wg.Done()
    for i := 1; i <= 4; i++ {
        orders <- fmt.Sprintf("%s's order %d", name, i)
    }
}

func boy(id int, orders <-chan string, delivered *int, mu *sync.Mutex, done chan<- struct{}) {
    for o := range orders { // ends when the owner closes orders
        mu.Lock()
        *delivered++
        mu.Unlock()
        _ = o
    }
    fmt.Println("boy", id, "finished")
    done <- struct{}{} // signal: this boy is done
}

func main() {
    orders := make(chan string)
    done := make(chan struct{})
    var wg sync.WaitGroup
    for _, c := range []string{"Raju", "Asha", "Neha"} {
        wg.Add(1)
        go cook(c, orders, &wg)
    }
    go func() { wg.Wait(); close(orders) }() // the owner closes, once

    delivered := 0
    var mu sync.Mutex
    go boy(1, orders, &delivered, &mu, done)
    go boy(2, orders, &delivered, &mu, done)
    <-done
    <-done
    fmt.Println("total delivered:", delivered)
    time.Sleep(10 * time.Millisecond)
    fmt.Println("goroutines alive:", runtime.NumGoroutine())
}

Real output (the order of the "finished" lines can swap):

boy 2 finished
boy 1 finished
total delivered: 12
goroutines alive: 1

Common mistakes (and the real messages)

Mistake Real message / result Why Fix
every sender closes the channel panic: send on closed channel no owner WaitGroup, then one close
closing twice panic: close of closed channel two closers one owner
the receiver closes panic: send on closed channel (in the sender) only senders know they're done the sender side closes
plain receive after close bill 3 = 0, total: 200 from 5 bills closed never blocks v, ok := <-ch or range
channel field never made deadlock! [chan receive (nil chan)] nil blocks forever make(chan T)
close on a nil channel panic: close of nil channel nothing to close make it first
taking only the first answer goroutines alive: 3 (no error at all) senders stuck forever buffer for every sender, or a stop signal
one send to wake many deadlock! [sync.WaitGroup.Wait], [chan receive] one value, one receiver close(done)
chan bool for a pure signal confusing code what does false mean? chan struct{}
reading hchan with unsafe in real code breaks on a Go upgrade private layout use len/cap

Practice

  1. What does this print?
package main

import "fmt"

func main() {
    var a chan int
    b := make(chan int, 1)
    b <- 5
    close(b)
    v, ok := <-b
    fmt.Println(v, ok)
    v, ok = <-b
    fmt.Println(v, ok)
    fmt.Println(a == nil, len(a), cap(a))
}
  1. Rewrite the two-cooks program so that each cook gets its own channel and main merges them. Who closes each channel now?
  2. Make the mandi example leak-free without a buffer.
  3. Write a "starting line": three goroutines wait on one channel, and one statement starts them all.
Solutions

1. Real output:

5 true
0 false
true 0 0

The buffered 5 comes out first with ok == true; then the closed, empty channel gives 0 false. A nil channel compares equal to nil and has len and cap 0.

2. Each cook owns its channel and closes it when done (one sender each, so rule 2 applies). main receives from each channel with range until both are closed (episode 49's select with nil channels does this without waiting on one channel at a time).

3. Give every sender a way out: a done channel closed after the first answer, and a select that either sends or gives up:

package main

import (
    "fmt"
    "runtime"
    "time"
)

func ask(supplier string, delay time.Duration, answer chan<- string, done <-chan struct{}) {
    time.Sleep(delay)
    select { // previewing next episode: send, or give up when told to stop
    case answer <- supplier:
    case <-done:
    }
}

func main() {
    answer := make(chan string) // still unbuffered
    done := make(chan struct{})
    go ask("Mandi A", 30*time.Millisecond, answer, done)
    go ask("Mandi B", 10*time.Millisecond, answer, done)
    go ask("Mandi C", 20*time.Millisecond, answer, done)
    fmt.Println("first answer:", <-answer)
    close(done) // broadcast: everyone else can stop
    time.Sleep(100 * time.Millisecond)
    fmt.Println("goroutines alive:", runtime.NumGoroutine())
}

4. Close a chan struct{}:

package main

import (
    "fmt"
    "sync"
)

func main() {
    start := make(chan struct{})
    var wg sync.WaitGroup
    for i := 1; i <= 3; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            <-start // all runners wait at the line
            fmt.Println("runner", i, "off!")
        }()
    }
    close(start) // one close starts everyone
    wg.Wait()
}

Real output (any order):

runner 3 off!
runner 1 off!
runner 2 off!

Quick quiz

1. A buffered channel holds 7, then it's closed. fmt.Println(<-ch, <-ch), then ch <- 8. What happens? (From the video.)

A. 7 0, then panic: send on closed channel · B. 7 7, then nothing · C. deadlock before printing · D. 7, then the program hangs

Answer

A. The buffered 7 is received first; the closed, empty channel then gives the zero value 0 at once; sending on a closed channel panics.

2. var ch chan int; ch <- 1 in main, with no other goroutines. What does Go print?

Answer

fatal error: all goroutines are asleep - deadlock! with goroutine 1 [chan send (nil chan)].

3. Why doesn't Go report the leaked mandi goroutines as a deadlock?

Answer

The detector only fires when every goroutine is blocked. main was still running, so the runtime can't know the senders will never be received.

4. Which wakes all of 10 goroutines blocked in <-done: done <- struct{}{} or close(done)?

Answer

close(done). One send wakes exactly one receiver.

Interview questions

  1. What happens when you send on a closed channel? Receive from one? Send panics (send on closed channel). Receive returns buffered values first, then the zero value immediately with ok == false.
  2. What do nil channels do, and why are they useful? Send and receive block forever, close panics. In a select, setting a channel to nil disables its case.
  3. Who should close a channel? The sender side, exactly once; with several senders, a coordinating owner closes after all senders finish (WaitGroup). Receivers never close.
  4. Do you have to close every channel? No. Close only to tell receivers no more values will come; unreachable channels are garbage collected.
  5. How do you check if a channel is closed? You don't, in general: there's no API, because the answer would be stale at once. Receive with comma-ok, or design ownership so you know.
  6. When does Go report "all goroutines are asleep - deadlock!"? When every goroutine is blocked. Partial deadlocks and leaks are not reported; use runtime.NumGoroutine, goroutine profiles (episode 57) or tests (episode 54).
  7. What is a goroutine leak and how do you avoid it? A goroutine that can never finish. Give every goroutine an exit: buffered result channels, done/context cancellation, closing input channels.
  8. Why chan struct{} for signals? The empty struct takes 0 bytes and makes it clear only the event matters.
  9. How is close a broadcast? A receive on a closed channel proceeds immediately for every receiver, so one close releases all waiters.
  10. What's inside a channel? An hchan: a circular buffer (buf, dataqsiz, qcount, sendx, recvx), the closed flag, wait queues of sudogs (sendq, recvq) and a lock. The channel value is a pointer to it.

Glossary

Term Meaning Example
Sender a goroutine that sends on a channel a cook
Receiver a goroutine that receives from a channel the delivery boy
Panic Go stopping the program for something that must never happen panic: send on closed channel
Stack trace the list of function calls printed with a panic, showing where it happened main.cook(...) main.go:11
Send on a closed channel always panics Asha's dish after Raju's close
Close of closed channel closing twice: panics two close(hatch)
Channel owner the goroutine responsible for making and closing a channel main owns the hatch
Ownership one owner per channel, one close WaitGroup then close
Closer goroutine a small goroutine that waits for senders and then closes go func() { wg.Wait(); close(hatch) }()
Zero value the default value of a type 0, "", nil
Comma-ok receive v, ok := <-ch; ok == false when closed and empty b, ok := <-bills
nil channel a channel variable that was never made var ch chan string
Block forever wait with no possible wake-up send on a nil channel
(nil chan) the runtime's note that a goroutine is blocked on a nil channel [chan receive (nil chan)]
Close of nil channel panics close(hatch) on a nil hatch
Axiom a basic rule everything else builds on "a send to a nil channel blocks forever"
Deadlock goroutines waiting for each other forever all goroutines are asleep
Deadlock detector the runtime check that fires when every goroutine is blocked fatal error: ... deadlock!
Goroutine leak a goroutine that can never finish two mandi senders
runtime.NumGoroutine() how many goroutines exist now, main included goroutines alive: 3
Signal channel a channel used only to say "now" ready := make(chan struct{})
Empty struct struct{} a struct type with no fields, size 0 struct{}{} is its value
unsafe.Sizeof how many bytes a value occupies unsafe.Sizeof(true) = 1
Broadcast one action every waiter notices close(home)
Runtime the part of Go inside every program that runs goroutines, memory, channels it creates the hchan
hchan the runtime structure behind a channel qcount, buf, sendq
Circular buffer a fixed array used round and round sendx wraps from 2 to 0
qcount values waiting in the buffer (len) qcount=3
dataqsiz buffer size (cap) dataqsiz=3
sendx, recvx the next slot to send into / receive from sendx=1 recvx=1
sendq, recvq queues of goroutines blocked sending / receiving waiting senders=true
sudog the runtime's record of one goroutine waiting on a channel an entry in sendq
unsafe a package that steps around Go's type safety unsafe.Pointer(&ch)

Summary

  • Send on a closed channel panics; closing twice or closing nil panics. Give each channel one owner on the sender side that closes it once (WaitGroup + closer goroutine for many senders). Receivers never close; you never have to close.
  • A receive on a closed channel returns buffered values, then the zero value at once: use comma-ok or range.
  • A nil channel blocks forever on send and receive (useful in select).
  • Go reports a deadlock only when every goroutine is blocked; stuck goroutines elsewhere are a silent leak. Every goroutine needs a way to end.
  • chan struct{} is a zero-byte signal; close is a broadcast to every receiver.
  • A channel is a pointer to an hchan: circular buffer, sendx/recvx, sendq/recvq of sudogs, and a lock.

Next episode: select, timeouts and timers: waiting on many channels at once, default for non-blocking operations, random choice, the for-select loop, switching cases off with nil channels, time.After, time.NewTimer with Stop and Reset, time.Ticker, heartbeats, and the Go 1.23 timer changes.