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:
Varun Narang 2021-12-31 23:31:35 +05:30 committed by GitHub
parent 668ecb9732
commit ccede75412
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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;