Channels & select
Definition
Channel
- In plain English
- A channel is a typed pipe that goroutines use to send values to each other safely.
- Think of it like
- It is like a pneumatic tube between offices: put a message in one end, it pops out the other.
select
- In plain English
- select lets a goroutine wait on several channel operations and run whichever is ready first.
- Think of it like
- It is like a receptionist watching several phone lines and answering whichever rings.
Why it exists
Kitchen stations need orders from several callers. Let one station own its queue and receive messages.
The callers pass values instead of editing that queue. You can also wait for work or a stop signal.
Panic
- In plain English
- A panic stops normal execution and ends the program unless code explicitly recovers.
- Think of it like
- Like an emergency stop that halts a machine.
How it works
Buffered vs unbuffered channel
- In plain English
- An unbuffered channel makes the sender wait until a receiver takes the value, while a buffered channel holds a few values so the sender can continue.
- Think of it like
- Like handing a parcel to someone in person versus dropping it in a mailbox with limited space.
Closing a channel
- In plain English
- Closing a channel tells receivers no more values will come, and only the sender should close it.
- Think of it like
- Like a shop flipping its sign to "closed".
Sender sends values through an Order channel to a receiver that owns its queue.
| Channel | Sender waits when | Useful for |
|---|---|---|
| Unbuffered | No receiver is ready | A direct handover |
| Buffered | The buffer is full | A bounded queue |
- A closed channel yields its buffered values first, then the zero value with ok equal to false.
- Range receives until the closed channel is drained. Sending on a closed channel panics.
- A nil channel has no channel assigned; its select case is disabled, while an ordinary send or receive blocks forever.
- If several select cases are ready, Go chooses one pseudo-randomly; source order gives no priority.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
accepted := make(chan string, 1)
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); time.Sleep(40 * time.Millisecond); accepted <- "ambulance 7" }()
select {
case id := <-accepted:
fmt.Println(id)
case <-time.After(30 * time.Millisecond):
fmt.Println("escalate")
}
wg.Wait()
}
The buffer holds one late response, so the helper cannot get stuck sending after a timeout. Wait still joins it.
Examples
Give the station ownership
Orders arrive through one channel. Only the receiving station changes its queue.
package main
import (
"fmt"
)
func main() {
orders := make(chan int)
go func() {
defer close(orders)
for id := 1; id <= 3; id++ {
orders <- id
}
}()
queue := []int{}
for id := range orders {
queue = append(queue, id)
}
fmt.Println(queue)
}
The range loop ends after the sender closes the channel. Nobody else touches queue.
The insight
One owner and a channel can replace shared-state locking.
Escalate a slow response
A dispatcher waits up to thirty seconds for acceptance. The demo shortens that delay.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
accepted := make(chan string, 1)
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); time.Sleep(40 * time.Millisecond); accepted <- "ambulance 7" }()
select {
case id := <-accepted:
fmt.Println(id)
case <-time.After(30 * time.Millisecond):
fmt.Println("escalate")
}
wg.Wait()
}
Expect escalation here, but scheduling can change which case is ready first. A real request should support cancellation too.
The insight
Select and a timer let the caller stop waiting.
Stop the control loop
The controller waits for readings. Closing stop tells it to exit.
package main
import (
"fmt"
)
func main() {
readings := make(chan int)
stop := make(chan struct{})
done := make(chan struct{})
go func() {
defer close(done)
for {
select {
case t := <-readings:
fmt.Println(t)
case <-stop:
return
}
}
}()
readings <- 21
close(stop)
<-done
}
Main receives done before returning. The controller closes done because it sends the completion signal.
The insight
Select handles work and stop signals together.
Trade-offs
Pros
- Make data ownership visible.
- Combine work and stop signals.
Cons
- Missing receivers can leave senders stuck.
- Channels do not protect objects shared through pointers.
Use when
- Transfer jobs or results between owners.
- Wait for work and a stop signal.
Avoid when
- One shared struct needs a short protected update.
- Extra channels hide a straightforward operation.
Quick check
Takeaways
- Channels transfer values between goroutines.
- Select waits on channel operations, including timer signals.
- The sending side closes after all sends finish.