What is the Advantage of sync.WaitGroup over Channels?

后端 未结 6 721
旧巷少年郎
旧巷少年郎 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:04

    Also suggest to use waitgroup but still you want to do it with channel then below i mention a simple use of channel

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        c := make(chan string)
        words := []string{"foo", "bar", "baz"}
    
        go printWordrs(words, c)
    
        for j := range c {
            fmt.Println(j)
        }
    }
    
    
    func printWordrs(words []string, c chan string) {
        defer close(c)
        for _, word := range words {
            time.Sleep(1 * time.Second)
            c <- word
        }   
    }
    

提交回复
热议问题