go - What is the Advantage of sync.WaitGroup over Channels? -


i'm working on concurrent go library, , stumbled upon 2 distinct patterns of synchronization between goroutines results similar:

using waitgroup

var wg sync.waitgroup func main() {         words := []string{ "foo", "bar", "baz" }          _, word := range words {                 wg.add(1)                 go func(word string) {                         time.sleep(1 * time.second)                         defer wg.done()                         fmt.println(word)                 }(word)         }         // concurrent things here          // blocks/waits waitgroup         wg.wait() } 

using channel

func main() {         words = []string{ "foo", "bar", "baz" }         done := make(chan bool)         defer close(done)         _, word := range words {                 go func(word string) {                         time.sleep(1 * time.second)                         fmt.println(word)                         done <- true                 }(word)         }          // concurrent things here          // blocks , waits signal channel         <-done } 

i advised sync.waitgroup more performant, , have seen being used commonly. however, find channels more idiomatic. real advantage of using sync.waitgroup on channels and/or might situation when better?

independantly of correctness of second example (as explained in comments, aren't doing think, it's fixable), tend think first example easier grasp.

now, wouldn't channels more idiomatic. channels being signature feature of go language shouldn't mean idiomatic use them whenever possible. idiomatic in go use simplest , easiest understand solution: here, waitgroup convey both meaning (your main function waiting workers done) , mechanic (the workers notify when done).

unless you're in specific case, don't recommand using channel solution here…


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -