Channel idioms
suggest changeChannels exhibit the following properties:
- send to a nil channel blocks forever
- receive from a nil channel blocks forever
- send to a closed channel panics
- receive from a closed channel returns a remaining buffered value, or the zero value immediately if the channel is empty
Send to a nil channel blocks forever
package main
func main() {
var ch chan bool
ch <- true // deadlocks because ch is nil
}
The zero value of a channel is nil, so the program above blocks forever.
A nil channel is useful inside select, where that case never fires and the others can still proceed. A send or receive on a nil channel by itself is almost always a bug.
Receive from a nil channel blocks forever
package main
import "fmt"
func main() {
var ch chan bool
fmt.Printf("Value received from ch is: %v\n", <-ch) // deadlock because ch is nil
}
A receive from a nil channel also blocks forever. As with send, that is a bug unless the nil channel is a disabled select case.
Send to a closed channel panics
package main
import (
"fmt"
"time"
)
func main() {
var ch = make(chan int, 100)
go func() {
ch <- 1
time.Sleep(time.Second)
close(ch)
ch <- 1
}()
for i := range ch {
fmt.Printf("i: %d\n", i)
}
}
i: 1
panic: send on closed channel
goroutine 5 [running]:
main.main.func1(0x452000, 0xc99)
/tmp/sandbox307976305/main.go:14 +0xa0
created by main.main
/tmp/sandbox307976305/main.go:10 +0x60
Structure the program so that one sender controls the lifetime of a channel.
If only one goroutine sends, that goroutine can close the channel and no sender will write after the close.
With multiple senders it is hard: if one of them closes the channel, the others can panic on send.
Prefer one sender that closes the channel. Do not close it from several goroutines.
Receive from a closed channel returns the zero value immediately
package main
import "fmt"
func main() {
// show
ch := make(chan int, 2)
ch <- 1
ch <- 2
close(ch)
for i := 0; i < 3; i++ {
fmt.Printf("%d ", <-ch) // -> 1 2 0
}
// show end
}
This is not ideal: we've read a value from a channel that was never sent.
It's easy to remedy:
package main
import "fmt"
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2
close(ch)
// show
for {
v, ok := <-ch
if !ok {
break
}
fmt.Printf("%d ", v) // -> 1 2
}
// show end
}
And even better and more idiomatically:
package main
import "fmt"
func main() {
ch := make(chan int, 2)
ch <- 1
ch <- 2
close(ch)
// show
for v := range ch {
fmt.Printf("%d ", v) // -> 1 2
}
// show end
}
Closing channel to signal a goroutine has finished
Sometimes you need to wait until a goroutine has finished.
The fact that a receive from a closed channel returns immediately but otherwise blocks can be used to coordinate between goroutines by a shared "done" channel.
One goroutine closes the channel at the end.
The other goroutine can wait until that happens by receiving: <-chDone
In more complex scenarios it can receive from multiple channels with select statement. For example, to limit a waiting time:
select {
case <- chDone:
// goroutine has finished
case <-time.After(time.Second * 5):
// goroutine didn't finish but we don't want to wait
// more than 5 seconds
}
To check whether an empty signaling channel is already closed, without waiting:
package main
import "fmt"
// show
func checkState(ch chan struct{}) {
select {
case <-ch:
fmt.Printf("channel is closed\n")
default:
fmt.Printf("channel is not closed\n")
}
}
// show end
func main() {
// show
ch := make(chan struct{})
checkState(ch)
close(ch)
checkState(ch)
// show end
}
A buffered value would also make that receive succeed, so use this only for a chan struct{} that is closed and never sent on. The same pattern is how a receive from context.Done reports cancellation.