Use the full power of closure.
Use the full power of closure by accepting the parameters to anonymous function being run by goroutine.
This commit is contained in:
parent
668ecb9732
commit
ccede75412
@ -29,19 +29,16 @@ func main() {
|
||||
// counter for each.
|
||||
for i := 1; i <= 5; i++ {
|
||||
wg.Add(1)
|
||||
// Avoid re-use of the same `i` value in each goroutine closure.
|
||||
// See [the FAQ](https://golang.org/doc/faq#closures_and_goroutines)
|
||||
// for more details.
|
||||
i := i
|
||||
|
||||
// Wrap the worker call in a closure that makes sure to tell
|
||||
// the WaitGroup that this worker is done. This way the worker
|
||||
// itself does not have to be aware of the concurrency primitives
|
||||
// involved in its execution.
|
||||
go func() {
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
worker(i)
|
||||
}()
|
||||
// use the incremental value of i in each different goroutine.
|
||||
}(i)
|
||||
}
|
||||
|
||||
// Block until the WaitGroup counter goes back to 0;
|
||||
|
Loading…
x
Reference in New Issue
Block a user