Middle+
What is a race condition in Go? Provide an example.
sobes.tech AI
Answer from AI
Data race (race condition) in Go is a situation where multiple goroutines access the same variable simultaneously without proper synchronization, and at least one of them modifies it. This leads to unpredictable program behavior.
Example of a data race:
package main
import (
"fmt"
"time"
)
func main() {
counter := 0
for i := 0; i < 1000; i++ {
go func() {
counter++ // Unsynchronized modification
}()
}
time.Sleep(time.Second)
fmt.Println("Counter:", counter) // Result may be less than 1000 due to the race
}
In this example, many goroutines simultaneously increment the counter variable without synchronization, leading to lost updates. To avoid races, use mutexes (sync.Mutex), channels, or other synchronization mechanisms.