Junior — Middle
Why can using variables for data exchange between goroutines lead to errors or problems?
sobes.tech AI
Answer from AI
Using variables for data exchange between goroutines without synchronization can lead to race conditions, where multiple goroutines read and write to the same variable simultaneously. This causes unpredictable program behavior, errors, and debugging difficulties.
For safe data exchange between goroutines in Go, it is recommended to use channels or synchronization mechanisms from the sync package (such as mutexes), which ensure proper access and prevent races.
Example of a problem with an unsynchronized variable:
var counter int
func increment() {
counter = counter + 1 // can lead to a race
}
func main() {
for i := 0; i < 1000; i++ {
go increment()
}
time.Sleep(time.Second)
fmt.Println(counter) // result may be less than 1000
}
Using a channel or mutex will solve this problem.