when you run follow code:
func l(ch chan int) {
println("l being")
ch<-1
println("l after write")
time.Sleep(time.Second*1)
println("l goroutine down")
}
func main() {
c := make(chan int)
go l(c)
println("main")
time.Sleep(time.Second*9)
println("main down")
}
you will get follow result
main
l being
main down
It mean's that sending data to chan will block the current go routine, i am surprised of this behaviour. i know read data from chan will block go routine, and it is easy understand. but sending data to chan block go routine, i don't think it is good enough, any guys can tell me why Go-Lang have this design to help me understand? thank you so much:)
You don't show the creation of the channel so I'm assuming it's unbuffered. An unbuffered channel can't hold onto any items, so the sender blocks until the item is received. If you create a buffered channel with a buffer size of n, a send operation won't block unless there are n items in the channel that haven't been received yet. To create a buffered channel, pass the buffer size to make
as follows:
c := make(chan int, 10)
See https://golang.org/doc/effective_go.html#channels for more information.