Sobes.tech
Middle+

Task 3: Find errors in code with goroutines, map, and WaitGroup.

sobes.tech AI

Answer from AI

When working with goroutines, maps, and sync.WaitGroup in Go, the following common mistakes often occur:

  1. Concurrent access to a map without synchronization — maps in Go are not thread-safe, and simultaneous read/write operations from different goroutines can cause a panic.

  2. Incorrect use of WaitGroup — for example, calling wg.Done() fewer or more times than wg.Add(), or calling wg.Wait() before all goroutines have started.

  3. Passing loop variables by reference to goroutines — all goroutines might get the same variable, leading to incorrect results.

Example of corrected code:

var mu sync.Mutex
var wg sync.WaitGroup
results := make(map[int]int)

for i := 0; i < 10; i++ {
    wg.Add(1)
    i := i // local copy of the variable
    go func() {
        defer wg.Done()
        value := i * 2
        mu.Lock()
        results[i] = value
        mu.Unlock()
    }()
}
wg.Wait()

Here:

  • A local copy of i is created for each goroutine.
  • A mutex mu is used for safe access to the map.
  • wg.Add(1) is called before starting the goroutine, and wg.Done() inside it.

This prevents data races and ensures the correct completion of all goroutines.