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 关于模型训练的一个问题
  • ¥15 装了几千台服务器从来没遇到这种问题,哎看下哪位帮我解决吧
  • ¥15 单片机程序上的困难问题
  • ¥15 请教某软件缓存Ts文件破解合并mp4的方法
  • ¥15 求小游戏炸弹人中关于敌人的C++代码
  • ¥15 拿到这个服务器最高权限有偿
  • ¥50 来个抓app跳转支付宝转链接的
  • ¥15 remotes安装提示没有description文件
  • ¥15 AttributeError: 'NoneType' object has no attribute 'drop_duplicates'报错
  • ¥15 以下代码,运行结果报错