Created
June 9, 2022 12:21
-
-
Save VinGarcia/6d9a2463e33d69b5d7d394bf3b91b129 to your computer and use it in GitHub Desktop.
Short Example of Race Condition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"time" | |
) | |
func main() { | |
var v1, v2, v3 int | |
var sharedInt int | |
stopSignal := false | |
doneCh := make(chan bool) | |
go func() { | |
time.Sleep(1 * time.Second) | |
stopSignal = true | |
}() | |
go func() { | |
for stopSignal == false { | |
v1++ | |
sharedInt++ | |
} | |
doneCh <- true | |
}() | |
go func() { | |
for stopSignal == false { | |
v2++ | |
sharedInt++ | |
} | |
doneCh <- true | |
}() | |
go func() { | |
for stopSignal == false { | |
v3++ | |
sharedInt++ | |
} | |
doneCh <- true | |
}() | |
for i := 0; i < 3; i++ { | |
<-doneCh | |
} | |
fmt.Println("all goroutines have stopped") | |
// Because of the race condition the sharedInt | |
// will be smaller than the sum of v1, v2 and v3: | |
fmt.Println("sharedInt: ", sharedInt) | |
fmt.Println("v1+v2+v3: ", v1+v2+v3) | |
// The reason for that is that when multiple goroutines | |
// are reading, incrementing and writing to the same variable | |
// they eventually will ignore or undo the work of the other | |
// goroutines, for example adding 30+1 in all 3 goroutines | |
// and then saving 31 3 times in sharedInt. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment