为什么将数据发送到无缓冲通道会阻塞 Go 协程?

huangapple go评论90阅读模式
英文:

Why sending data to no buffered chan will block the go routine

问题

当你运行以下代码时:

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")
}

你将得到以下结果:

main
l being
main down

这意味着向通道发送数据会阻塞当前的 Go 协程,我对这种行为感到惊讶。我知道从通道读取数据会阻塞 Go 协程,这很容易理解。但是发送数据到通道会阻塞 Go 协程,我认为这不够好,有人可以告诉我为什么 Go 语言设计成这样吗?谢谢你!:)

英文:

when you run follow code:

func l(ch chan int)  {
    println(&quot;l being&quot;)
    ch&lt;-1

    println(&quot;l after write&quot;)
    time.Sleep(time.Second*1)
    println(&quot;l goroutine down&quot;)
}

func main() {
    c := make(chan int)
    go l(c)
    println(&quot;main&quot;)

    time.Sleep(time.Second*9)
   println(&quot;main down&quot;)
}

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:)

答案1

得分: 3

你没有展示创建通道的过程,所以我假设它是无缓冲的。无缓冲通道不能保存任何项目,因此发送者会阻塞,直到接收到项目。如果你创建一个带有大小为n的缓冲通道,发送操作只有在通道中有n个尚未接收的项目时才会阻塞。要创建一个带有缓冲的通道,请将缓冲大小传递给make函数,如下所示:

c := make(chan int, 10)

有关更多信息,请参阅https://golang.org/doc/effective_go.html#channels。

英文:

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.

huangapple
  • 本文由 发表于 2017年2月21日 11:16:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/42358000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定