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:
-
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.
-
Incorrect use of WaitGroup — for example, calling
wg.Done()fewer or more times thanwg.Add(), or callingwg.Wait()before all goroutines have started. -
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
iis created for each goroutine. - A mutex
muis used for safe access to the map. wg.Add(1)is called before starting the goroutine, andwg.Done()inside it.
This prevents data races and ensures the correct completion of all goroutines.