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 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名