3 ms·
I don't like this example and solution, because while it doesn't leaks (the channel goes out of scope, and the goroutine ends) it still is 1. error prone you no
by nemothekid 8y ago
I don't like this example and solution, because while it doesn't leaks (the channel goes out of scope, and the goroutine ends) it still is 1. error prone you now have to have a buffered channel, 2. sort of wasteful, setting the buffer to 1 instead of 2, also wouldn't leak and 3. not clear.
If you don't care about the results of the goroutine (here you explicitly don't care about the return value of at least one of the routines), a WaitGroup is much better.
import "sync"
func doSomethingTwice() error {
// Issue occurs below
var wg sync.WaitGroup()
wg.Add(1)
go func() {
defer fmt.Println("done wth a")
wg.Done()
}()
wg.Add(1)
go func() {
defer fmt.Println("done with b")
wg.Done()
}()
wg.Wait()
return nil
}
The more advanced concept than this, which isn't in the stdlib is errgroup (https://godoc.org/golang.org/x/sync/errgroup#Group.Wait https://godoc.org/golang.org/x/sync/errgroup#Group.Wait), where instead the accompayning `Wait()` function can also return an error.
In general I consider a code smell if you aren't reading every value off the channel.