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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失