douwang9650 2019-01-13 05:22
浏览 60
已采纳

一个通道带有一个接收器,未知数量的goroutine发送器导致死锁

I have one channel and the receiver is main. I spawn multiple goroutines that each send a string over the channel.

Now, this causes a deadlock because I didn't close the channel properly using the close function. The thing is, I have no idea how many goroutines will be created, so there's no way to know when to close the channel.

I've tried using WaitGroup, the problem is, I've read that I can't use Add in the goroutine and that I should use wg.Add(1) in the main process/goroutine, I've tried using Add in the parent goroutine spawning the child goroutine, that also caused a deadlock

package main

import (
    "fmt"
    "sync"
)

var i = 0

func doSomething(ch chan string, wg sync.WaitGroup) {
    defer wg.Done()
    ch <- fmt.Sprintf("doSomething: %d", i)
    i++
    if i == 10 {return}
    wg.Add(1)
    go doSomething(ch, wg)
}

func main() {
    ch := make(chan string)
    var wg sync.WaitGroup
    wg.Add(1)
    go doSomething(ch, wg)
    wg.Wait()
    for s := range ch {
        fmt.Println(s)
    }
}

Now, this is just a test code, so, assume that we don't know that we will create 10 goroutines only, assume that it's unknown at runtime, here I get a deadlock error instantly without any output, if I don't use WorkGroup I get the error at before printing the 10th string (because I didn't close the channel)

I've also tried not spawning a goroutine for each function call and instead use one goroutine for all the recursive calls (starting from main), and to close the channel, I made an anonymous function for go that first calls the doSomething function then calls close, so all the recursive calls will have been evaluated and we will for sure know when to close the channel. But, this is now what I'm trying to accomplish, I'm trying to get the unknown number of goroutines to work together and close the channel after they're done somehow.

  • 写回答

1条回答 默认 最新

  • drmqzb5063 2019-01-13 06:05
    关注

    There are a few issues.

    The first is that the program copies wait group values when passing them as arguments. Wait groups don't work correctly when copied. Pass pointer to a wait group instead.

    The second issue is that main waits for all of the goroutines complete before receiving values from the channels. Because the channel's buffer is not large enough to hold all sent values, the program deadlocks.

    A third issue is that main ranges over the channel, but nothing ever closes the channel. Main will not exit as a result.

    To fix the second and third issues, start another goroutine to wait on doSomthings and close the channel when they are done.

    Try this:

    func doSomething(ch chan string, wg *sync.WaitGroup) {
        defer wg.Done()
        ch <- fmt.Sprintf("doSomething: %d", i)
        i++
        if i == 10 {
            return
        }
        wg.Add(1)
        go doSomething(ch, wg)
    }
    
    func main() {
        ch := make(chan string)
        var wg sync.WaitGroup
        wg.Add(1)
        go doSomething(ch, &wg)
        go func() {
            wg.Wait()
            close(ch)
        }()
        for s := range ch {
            fmt.Println(s)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻看一个题
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)