donglie1898 2017-02-07 08:38
浏览 7
已采纳

Go中的频道死锁

I am getting "fatal error: all goroutines are asleep - deadlock! " for some reason in the below code. I am using buffered channel which should be non-blocking. Not sure what I am doing wrong

package main

import (
    "fmt"
    "sync"
)

func main() {
    c := make(chan int, 2)
    var wg sync.WaitGroup
    wg.Add(2)

    go doSomething(c, wg)
    go doSomething(c, wg)
    go doSomething(c, wg)

    wg.Wait()

    close(c)

    for v := range c {
        fmt.Print(v)
    }

}

func doSomething(c chan<- int, wg sync.WaitGroup) {
    defer wg.Done()
    c <- 1

}

Playground link https://play.golang.org/p/J9meD5aKna

  • 写回答

3条回答 默认 最新

  • dqkmn26444 2017-02-07 10:06
    关注

    While your solution might work I'm not happy with it.

    First, the fact that you need to change the channel size to make it work indicates that there is a potential problem / bug. Now each time you want to launch another doSomething you have to remember to change channel's length.

    Second, you wait until all the goroutines are finished before reading from the channel. This is kind of "waste" as one of the main points of range loop over an channel is that you don't have to wait until all the items are generated (written into channel), you can start processing the items as soon as some of them are ready.

    So I would write your code as something like

    func main() {
        c := make(chan int)
    
        var wg sync.WaitGroup
        wg.Add(3)
        go func() {
            doSomething(c)
            defer wg.Done()
        }()
        go func() {
            doSomething(c)
            defer wg.Done()
        }()
        go func() {
            doSomething(c)
            defer wg.Done()
        }()
    
        go func() {
            wg.Wait()
            defer close(c)
        }()
    
        for v := range c {
            fmt.Print(v)
        }
    }
    
    func doSomething(c chan<- int) {
        c <- 1
    }
    

    https://play.golang.org/p/T3dfiztKot

    Note how the waiting and closing the channel is now in it's own goroutine - this allows to start iterating over the channel (which is now unbuffered!) right away.

    I also changed the code so that the WaitGroup never leaves the scope where it is declared (ie it isn't used as parameter), this is my personal preference. I believe it makes code easier to follow and understand.

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

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法