dounanyin3179 2017-07-07 12:25
浏览 45
已采纳

进行并发,所有goroutine都处于睡眠状态-死锁

Sorry about the noob question but I'm having a hard time wrapping my head around the concurrency part of go. Basically this program below is a simplified version of a larger one I'm writing, thus I want to keep the structure similar to below.

Basically instead of waiting 4 seconds I want to run addCount(..) concurrent using the unbuffered channel and when all elements in the int_slice has been processed I want to do another operation on them. However this program ends with a "panic: close of closed channel" and if I remove the closing of the channel I'm getting the output I'm expecting but it panics with: "fatal error: all goroutines are asleep - deadlock"

How can I implement the concurrency part correctly in this scenario?

Thanks in advance!

package main

import (
    "fmt"
    "time"
)

func addCount(num int, counter chan<- int) {
    time.Sleep(time.Second * 2)
    counter <- num * 2
}

func main() {
    counter := make(chan int)
    int_slice := []int{2, 4}

    for _, item := range int_slice {
        go addCount(item, counter)
        close(counter)
    }

    for item := range counter {
        fmt.Println(item)
    }
}
  • 写回答

3条回答 默认 最新

  • dsft8327 2017-07-07 13:04
    关注

    Here are the issues I spotted in the code, and below a working version based on your implementation.

    • If a goroutine tries to write to an "unbuffered" channel, it will block until someone reads from it. Since you are not reading until they finish writing to the channel, you have a deadlock there.

    • Closing the channel while they are blocked breaks the deadlock, but gives an error since they now can't write to a closed channel.

    Solution involves:

    • Creating a buffered channel so that they can write without blocking.

    • Using a sync.WaitGroup so that you wait for the goroutines to finish before closing the channel.

    • Reading from the channel at the end, when all is done.

    See here, with comments:

        package main
    
        import (
            "fmt"
            "time"
            "sync"
        )
    
        func addCount(num int, counter chan<- int, wg *sync.WaitGroup) {
            // clear one from the sync group
            defer wg.Done()
            time.Sleep(time.Second * 2)
            counter <- num * 2
        }
    
        func main() {
            int_slice := []int{2, 4}
            // make the slice buffered using the slice size, so that they can write without blocking
            counter := make(chan int, len(int_slice))
    
            var wg sync.WaitGroup
    
            for _, item := range int_slice {
                // add one to the sync group, to mark we should wait for one more
                wg.Add(1)
                go addCount(item, counter, &wg)
            }
    
            // wait for all goroutines to end
            wg.Wait()
    
            // close the channel so that we not longer expect writes to it
            close(counter)
    
            // read remaining values in the channel
            for item := range counter {
                fmt.Println(item)
            }
    
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#vscode#的问题:ESP32开发板对接MQTT实现小灯泡的开关
  • ¥15 TMC2209串口模式下读取不到寄存器的值串口助手蓝色字体是发过去的消息,绿色字体是收到的消息,第二行发送读取寄存器的指令但是没有读取到寄存器的值串口助手如下图:接线如下图,如何解决?
  • ¥15 高通安卓11提取完整线刷包软件,或者优博讯dt50顺丰刷机包
  • ¥20 C,有个译码器,换了信道就跑不出原来数据
  • ¥15 MIMIC数据库安装问题
  • ¥60 基于JTag协议开发Fpga下载器上位机,哪位大🐂有偿指导?
  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题
  • ¥100 房产抖音小程序苹果搜不到安卓可以付费悬赏