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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)