Introduction to Channels
Channels are typed, thread-safe queues that allow different goroutines to communicate with each other and synchronize their execution.
Creating a Channel
Like maps and slices, channels must be created with make.
ch := make(chan int)
Channel Operations
The <- operator is used to move data in the direction of the arrow.
- Send:
ch <- 42(Pushes value into the channel) - Receive:
v := <-ch(Pops value out of the channel)
Blocking Behavior
By default, sends and receives are blocking:
- A send blocks until another goroutine is ready to receive.
- A receive blocks until there is data in the channel to be read.
Deadlocks
A deadlock occurs when all running goroutines are blocked waiting for each other. Go can often detect this at runtime and will panic to alert you.
Signalling
Sometimes you don’t need to pass data, just a signal that something happened. In these cases, it’s common to use an empty struct chan struct{} because it consumes zero memory.
done := make(chan struct{})
go func() {
// do work...
done <- struct{}{} // Signal completion
}()
<-done // Wait for signal