dongxianji0968 2016-08-16 13:33
浏览 37
已采纳

使用goroutine和闭包通过通道从并发函数读取并给出错误

I have a function (not a closure) that is writing to a channel. I am invoking that function from a goroutine as

var wg sync.WaitGroup
wg.Add(1)
go DoStuff(somechan, &wg)

Inside DoStuff, I have something like

for ; ; {

    if err == io.EOF { 
        fmt.Println(err)
        close(somechan)
        fmt.Println("Closed channel")
        break
    } else if err != nil {
        panic(err)
    }
    somechan <- Somefunc()
}

Now I am trying to read from that channel using another goroutine.

wgread.Add(1)
go func() {
    for ; ; {
        select {
        case chanoutput, ok := <-somechan:
            if ok == true {
                fmt.Println(string(*chanoutput))
            } else {
                fmt.Println("DONE")
                fmt.Println(ok)
                wgread.Done()
                break
            }
        }

    }
}()
wgread.Wait()

However, when running, I am getting

panic: sync: negative WaitGroup counter

after printing

DONE
false
DONE
false

If I give wgread.Add(2), it will print the above DONE and false 3 times.

Why is is giving a negative waitgroup counter error though I incremented the waitgroup delta by 1? What is the best way to read from a goroutine using another concurrent function or a closure?

  • 写回答

2条回答 默认 最新

  • doudunyi3796 2016-08-16 13:42
    关注

    The break statement breaks out of the inner most case, for or switch statement. The function that receives on somechan spins in a loop decrementing the wait group when the channel closes. Write the code like this:

    wgread.Add(1)
    go func() {
        defer wgread.Done()
        for chanoutput := range somechan {
            fmt.Println(string(*chanoutput))
        }
        fmt.Println("DONE")
    }()
    wgread.Wait()
    

    If the receiving code is as written in the question, then the receiving goroutine can eliminated. Replace the code from wgread.Add(1) to wgread.Wait() with

    for chanoutput := range somechan {
        fmt.Println(string(*chanoutput))
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧