duanoucuo7045 2016-04-04 15:46
浏览 24
已采纳

将sync.WaitGroup与外部功能配合使用的最佳方法

I have some issues with the following code:

package main

import (
"fmt"
"sync"
)
// This program should go to 11, but sometimes it only prints 1 to 10.
func main() {
    ch := make(chan int)
    var wg sync.WaitGroup
    wg.Add(2)
    go Print(ch, wg) //
    go func(){

        for i := 1; i <= 11; i++ {
            ch <- i
        }

        close(ch) 
        defer wg.Done()


    }()

    wg.Wait() //deadlock here
}

// Print prints all numbers sent on the channel.
// The function returns when the channel is closed.
func Print(ch <-chan int, wg sync.WaitGroup) {
    for n := range ch { // reads from channel until it's closed
        fmt.Println(n)
    }
    defer wg.Done()
}

I get a deadlock at the specified place. I have tried setting wg.Add(1) instead of 2 and it solves my problem. My belief is that I'm not successfully sending the channel as an argument to the Printer function. Is there a way to do that? Otherwise, a solution to my problem is replacing the go Print(ch, wg)line with:

go func() {
Print(ch)
defer wg.Done()
}

and changing the Printer function to:

func Print(ch <-chan int) {
    for n := range ch { // reads from channel until it's closed
        fmt.Println(n)
    }

}

What is the best solution?

  • 写回答

2条回答 默认 最新

  • dongshanyan0322 2016-04-04 15:55
    关注

    Well, first your actual error is that you're giving the Print method a copy of the sync.WaitGroup, so it doesn't call the Done() method on the one you're Wait()ing on.

    Try this instead:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func main() {    
        ch := make(chan int)
    
        var wg sync.WaitGroup
        wg.Add(2)    
    
        go Print(ch, &wg)
    
        go func() {  
            for i := 1; i <= 11; i++ {
                ch <- i
            }
            close(ch)
            defer wg.Done()
        }()          
    
        wg.Wait() //deadlock here
    }                
    
    func Print(ch <-chan int, wg *sync.WaitGroup) {
        for n := range ch { // reads from channel until it's closed
            fmt.Println(n)
        }            
        defer wg.Done()
    }
    

    Now, changing your Print method to remove the WaitGroup of it is a generally good idea: the method doesn't need to know something is waiting for it to finish its job.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备