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

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改