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

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化