doukeng7426 2017-02-21 03:16
浏览 22
已采纳

为什么将数据发送到没有缓冲的通道会阻塞执行例程

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

  • 写回答

1条回答 默认 最新

  • dongluan5740 2017-02-21 03:40
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog