Let's say I need to call a function twice. The usual way to do it would be:
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
doSomething(A)
wg.Done()
}()
go func() {
doSomething(B)
wg.Done()
}()
wg.Wait()
}
But what about writing it like this ?
func main() {
var wg sync.WaitGroup
wg.Add(2)
go func() {
doSomething(A)
wg.Done()
}()
doSomething(B)
wg.Done()
wg.Wait()
}
We spare ourselves the creation of one goroutines, while making use of the main goroutine. But I've never seen it written like that in any tutorial. Is it wrong to do this? I've done tests and the output are just as I though the same.
wg.Add(2)
instead of justwg.Add(1)
, then eliminate thewg.Done()
in main(). The main reason for the first version, IMO, would be readability. It's more clear what you're doing in the first version.doSomething()
is. At first glance, the first option is easier to grasp since the nesting levels are the same. Moreover, unless proven by your tests that one more goroutine is causing you slow runtimes, then prefer simplicity. Note that goroutines should be cheap. Goroutines are far cheaper than OS threads.