Best way of using sync.WaitGroup with external function

前端 未结 2 1165
名媛妹妹
名媛妹妹 2021-01-31 00:18

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         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-31 00: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.

提交回复
热议问题