dongnuoyi8833 2018-01-12 09:13
浏览 119
已采纳

Golang无缓冲通道大小?

Here is an example of book go in action https://github.com/goinaction/code/blob/master/chapter2/sample/search/search.go

    // Launch a goroutine to monitor when all the work is done.
    go func() {
        // Wait for everything to be processed.
        waitGroup.Wait()

        // Close the channel to signal to the Display
        // function that we can exit the program.
        close(results)
    }()

    // Start displaying results as they are available and
    // return after the final result is displayed.
    Display(results)

If I move waitGroup.Wait() and close(results) out of the goroutine function, program is blocked because the results in channel are not read yet, and it blocks at writing other more result into channel after it gets to a "size". But if I use a big size buffered channel:

results := make(chan *Result, 100)

program recovers back to normal. It seems that channel is blocked due to size limit and can not write more before consuming it. Is there a size limit for unbeffered channel ? why it writes a few messages into channel and decreases WaitGroup counter a little, then blocks itself at there ?

  • 写回答

3条回答 默认 最新

  • dougou1943 2018-01-12 09:33
    关注

    An unbuffered channel by definition doesn't have a buffer size. Sending blocks if there is something to read. Please take the go tour to familiarize yourself.

    The reason the code above blocks is that you are waiting for the WaitGroup counter to reach zero. I assume this is done after the goroutines (the ones you don't show) are done writing to the channel. One of them writes, but all others are blocking. Display is supposed to read from the channel (you also don't show that code), but never gets called. This means that nothing is ever consuming from the channel.

    Changing to a size 100 channel is only a temporary workaround. If you send more than 100 elements to the channel, it will still block as nothing is reading from it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度