I had a task to simulate race conditions in Go. However, I've run into a case, that I am unable to explain. The code snippet below
package main
import (
"fmt"
"sync"
)
var value, totalOps, totalIncOps, totalDecOps int
func main() {
fmt.Println("Total value: ", simulateRacing(10000))
fmt.Print("Total iterations: ", totalOps)
fmt.Print(" of it, increments: ", totalIncOps)
fmt.Print(", decrements: ", totalDecOps)
}
// Function to simulate racing condition
func simulateRacing(iterationsNumber int) int {
value = 0
// Define WaitGroup
var waitGroup sync.WaitGroup
waitGroup.Add(2)
go increaseByOne(iterationsNumber, &waitGroup)
go decreaseByOne(iterationsNumber, &waitGroup)
waitGroup.Wait()
return value
}
// Function to do N iterations, each time increasing value by 1
func increaseByOne(N int, waitGroup *sync.WaitGroup) {
for i := 0; i < N; i++ {
value++
// Collecting stats
totalOps++
totalIncOps++
}
waitGroup.Done()
}
// Same with decrease
func decreaseByOne(N int, waitGroup *sync.WaitGroup) {
for i := 0; i < N; i++ {
value--
// Collecting stats
totalOps++
totalDecOps++
}
waitGroup.Done()
}
In my understanding, it should produce consistent (deterministic) result each time, since we are doing the same number of increments and decrements, with a WaitGroup making sure both functions will execute.
However, each time output is different, with only increments and decrements counters staying the same. Total value: 2113 Total iterations: 17738 of it, increments: 10000, decrements: 10000 and Total value: 35 Total iterations: 10741 of it, increments: 10000, decrements: 10000
Maybe you can help me to explain this behaviour? Why total iterations counter and value itself is non-deterministic?