What is the Advantage of sync.WaitGroup over Channels?

后端 未结 6 715
旧巷少年郎
旧巷少年郎 2021-01-30 10:33

I\'m working on a concurrent Go library, and I stumbled upon two distinct patterns of synchronization between goroutines whose results are similar:

Waitgroup



        
6条回答
  •  囚心锁ツ
    2021-01-30 11:03

    I often use channels to collect error messages from goroutines that could produce an error. Here is a simple example:

    func couldGoWrong() (err error) {
        errorChannel := make(chan error, 3)
    
        // start a go routine
        go func() (err error) {
            defer func() { errorChannel <- err }()
    
            for c := 0; c < 10; c++ {
                _, err = fmt.Println(c)
                if err != nil {
                    return
                }
            }
    
            return
        }()
    
        // start another go routine
        go func() (err error) {
            defer func() { errorChannel <- err }()
    
            for c := 10; c < 100; c++ {
                _, err = fmt.Println(c)
                if err != nil {
                    return
                }
            }
    
            return
        }()
    
        // start yet another go routine
        go func() (err error) {
            defer func() { errorChannel <- err }()
    
            for c := 100; c < 1000; c++ {
                _, err = fmt.Println(c)
                if err != nil {
                    return
                }
            }
    
            return
        }()
    
        // synchronize go routines and collect errors here
        for c := 0; c < cap(errorChannel); c++ {
            err = <-errorChannel
            if err != nil {
                return
            }
        }
    
        return
    }
    

提交回复
热议问题