Goroutine Closures

What will be printed when the code below is executed?And fix the issue to assure that len(m) is printed as 10.

  1. package main
  2. import (
  3. "sync"
  4. )
  5. const N = 10
  6. func main() {
  7. m := make(map[int]int)
  8. wg := &sync.WaitGroup{}
  9. mu := &sync.Mutex{}
  10. wg.Add(N)
  11. for i := 0; i < N; i++ {
  12. go func() {
  13. defer wg.Done()
  14. mu.Lock()
  15. m[i] = i
  16. mu.Unlock()
  17. }()
  18. }
  19. wg.Wait()
  20. println(len(m))
  21. }

Answer

  1. package main
  2. import (
  3. "sync"
  4. )
  5. const N = 10
  6. func main() {
  7. m := make(map[int]int)
  8. wg := &sync.WaitGroup{}
  9. mu := &sync.Mutex{}
  10. wg.Add(N)
  11. for i := 0; i < N; i++ {
  12. go func(i int) {
  13. defer wg.Done()
  14. mu.Lock()
  15. m[i] = i
  16. mu.Unlock()
  17. }(i)
  18. }
  19. wg.Wait()
  20. println(len(m))
  21. }