dou5454954610 2019-04-16 11:24
浏览 25
已采纳

Golang频道并发问题

I am experimenting with channel concept in Golang. I wrote the below program playground to implement counter using channels. But I am not getting any output, although I am doing some printing in the goroutine body.

func main() {
    wg := sync.WaitGroup{}
    ch := make(chan int)

    count := func(ch chan int) {
        var last int
        last = <-ch
        last = last + 1
        fmt.Println(last)
        ch <- last
        wg.Done()
    }

    wg.Add(10)
    for i := 1; i <= 10; i++ {
        go count(ch)

    }
}

I expect at least some output but I am getting none at all.

  • 写回答

2条回答 默认 最新

  • doutandusegang2961 2019-04-16 11:31
    关注

    When the main() function (the main goroutine) ends, your program ends as well (it doesn't wait for other non-main goroutines to finish). You must add a wg.Wait() call to the end. See No output from goroutine in Go.

    Once you do this, you'll hit a deadlock. This is because all goroutines start with attempting to receive a value from the channel, and only then would they send something.

    So you should first send something on the channel to let at least one of the goroutines to proceed.

    Once you do that, you'll see numbers printed 10 times, and again deadlock. This is because when the last goroutine tries to send its incremented number, there will be no one to receive that. An easy way to fix that is to give a buffer to the channel.

    Final, working example:

    wg := sync.WaitGroup{}
    ch := make(chan int, 2)
    
    count := func(ch chan int) {
        var last int
        last = <-ch
        last = last + 1
        fmt.Println(last)
        ch <- last
        wg.Done()
    }
    
    wg.Add(10)
    for i := 1; i <= 10; i++ {
        go count(ch)
    
    }
    go func() {
        ch <- 0
    }()
    wg.Wait()
    

    Outputs (try it on the Go Playground):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    

    Also note that since we made the channel buffered, it's not necessary to use another goroutine to send an initial value, we can do that in the main goroutine:

    ch <- 0
    wg.Wait()
    

    This will output the same. Try it on the Go Playground.

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能