dougou7782 2016-06-21 11:21
浏览 33
已采纳

等待同步.Waitgroup推迟

I have the following code that goes into deadlock when sending on channel from a goroutine below:

package main

import (
    "fmt"
    "sync"
)

func main() {
    for a := range getCh(10) {
        fmt.Println("Got:", a)
    }
}

func getCh(n int) <-chan int {
    var wg sync.WaitGroup
    ch := make(chan int)
    defer func() {
        fmt.Println("closing")
        wg.Wait()
        close(ch)
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        for i := 0; i < n; i++ {
            ch <- i
        }
    }()
    wg.Add(1)
    go func() {
        defer wg.Done()
        for i := n; i < 0; i-- {
            ch <- i
        }
    }()

    return ch
}

I know that it is legal to use wg.Wait() in defer. But I haven't been able to find a use in a function with channel as a return value.

  • 写回答

2条回答 默认 最新

  • doushi1912 2016-06-21 12:20
    关注

    I think the mistake you're making is that you think that the deferred function will run asynchronously too. But that is not the case, so the getCh() will block in its deferred part, waiting for the WaitGroup. But as there is no one reading from the channel, the goroutines which write into it can't return and thus the WaitGroup causes deadlock. Try something like this:

    func getCh(n int) <-chan int {
        ch := make(chan int)
        go func() {
            var wg sync.WaitGroup
            wg.Add(1)
            go func(n int) {
                defer wg.Done()
                for i := 0; i < n; i++ {
                    ch <- i
                }
            }(n)
            wg.Add(1)
            go func(n int) {
                defer wg.Done()
                for i := n; i > 0; i-- {
                    ch <- i
                }
            }(n)
            wg.Wait()
            fmt.Println("closing")
            close(ch)
        }()
    
        return ch
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line