multithreadingingo
multithreadingingo copied to clipboard
Race condition example in stingy_spendy does not work
I use golang 1.17. And this code 8e48ac5638a972ffd4b003b88379949e691edbe8 to simulate race condition.
For each run I always get 100
but there should be different numbers.
What might be wrong? Don't we need locking anymore?
Hi, You always need synchronization mechanisms, whatever language you are using. This is the same in go lang 1.17. I tried running your code using 1.17 and I manage to reproduce a race condition by increasing the loop count and removing the sleep. This is to increase the chances of the race condition happening:
package main
import "time"
var (
money = 100
)
func stingy() {
for i := 1; i <= 100000; i++ {
money += 10
//time.Sleep(1 * time.Millisecond)
}
println("Stingy Done")
}
func spendy() {
for i := 1; i <= 100000; i++ {
money -= 10
//time.Sleep(1 * time.Millisecond)
}
println("Spendy Done")
}
func main() {
go stingy()
go spendy()
time.Sleep(2000 * time.Millisecond)
print(money)
}
When I run it I get:
go run sync\stingy_spendy.go
Stingy Done
Spendy Done
-517960
Thank you, now the simulation is working.