You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Frequently when you are using WaitGroup you do:
var wg sync.WaitGroup
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
for v := range in {
out <- v * v
}
wg.Done()
}()
}
go func() {
wg.Wait()
close(out)
}()
It would be nice to do it w/o the helper goroutine:
var wg sync.WaitGroup
wg.Add(N)
for i := 0; i < N; i++ {
go func() {
for v := range in {
out <- v * v
}
if wg.Done() {
close(out)
}
}()
}
I.e. WaitGroup.Done/Add return true when the counter drops to zero.
This breaks backward compatibility (var f func() = wg.Done), so marking "Go2".
The text was updated successfully, but these errors were encountered:
I'm worried that will lead to people write racy code such as the following:
var wg sync.WaitGroup
for i := 0; i < N; i {
wg.Add(1)
go func() {
...
if wg.Done() {
close(out)
}
}
}
This frequent can be remedied with a function:
func Spawn(N int32, fn func(id int), autoclose ...interface{}) {
var counter int32 = N
for k := 0; k < int(N); k += 1 {
go func(k int) {
fn(k)
if atomic.AddInt32(&counter, -1) == 0 {
for _, ch := range autoclose {
reflect.ValueOf(ch).Close()
}
}
}(k)
}
}
And the usage example: http://play.golang.org/p/8M156uFYPW.
Alternatively, the last parameter can be a callback to cleanup:
func Spawn(N int32, fn func(id int), whendone ...func()) {
var counter int32 = N
for k := 0; k < int(N); k += 1 {
go func(k int) {
fn(k)
if atomic.AddInt32(&counter, -1) == 0 {
for _, fn := range whendone {
fn()
}
}
}(k)
}
}
The text was updated successfully, but these errors were encountered: