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 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式