From ccede754122619134ab3def5766b5c4aeb524054 Mon Sep 17 00:00:00 2001 From: Varun Narang <904409+varunarang@users.noreply.github.com> Date: Fri, 31 Dec 2021 23:31:35 +0530 Subject: [PATCH] Use the full power of closure. Use the full power of closure by accepting the parameters to anonymous function being run by goroutine. --- examples/waitgroups/waitgroups.go | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/examples/waitgroups/waitgroups.go b/examples/waitgroups/waitgroups.go index 5ac70b5..d67f463 100644 --- a/examples/waitgroups/waitgroups.go +++ b/examples/waitgroups/waitgroups.go @@ -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;