Last active
August 29, 2015 14:07
-
-
Save hSATAC/cf4ec72eecb8d14faa4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
type Callback func() int | |
func doSomething() {} | |
func callbackFactory(i int) Callback { | |
return func() int { | |
fmt.Println("callback", i) | |
return i | |
} | |
} | |
var callbacks []Callback = []Callback{ | |
callbackFactory(1), | |
callbackFactory(2), | |
callbackFactory(3), | |
callbackFactory(4)} | |
func combiner(result int) { | |
sum += result | |
} | |
var sum int | |
func main() { | |
sum = 0 | |
ch := make(chan int, len(callbacks)) | |
var wg sync.WaitGroup | |
for _, callback := range callbacks { | |
wg.Add(1) | |
doSomething() | |
go func(callback Callback) { | |
ch <- callback() | |
}(callback) | |
} | |
go func() { | |
for c := range ch { | |
combiner(c) | |
wg.Done() | |
} | |
}() | |
wg.Wait() | |
fmt.Println("sum", sum) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment