Middle
There is a thread safety issue: if two goroutines call Lock simultaneously, they may interleave. How to fix this?
sobes.tech AI
Answer from AI
The problem occurs because two goroutines enter the critical section simultaneously, and their loops get mixed, violating thread safety.
To fix this, a mutex (sync.Mutex) should be used to synchronize access. The mutex ensures that only one goroutine can execute the code inside Lock at a time.
Example:
var mu sync.Mutex
func criticalSection() {
mu.Lock()
defer mu.Unlock()
for i := 0; i < 10; i++ {
// critical work
fmt.Println(i)
}
}
Thus, if two goroutines call criticalSection, one will wait until the other finishes executing the loop, preventing mixing.