Map Mutex

Fix the issue below to avoid "concurrent map writes" error.

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

Answer

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