Created
February 27, 2020 21:38
-
-
Save mannion007/190ac9da645e885638400a28b166a443 to your computer and use it in GitHub Desktop.
Go Race condition
This file contains 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" | |
"runtime" | |
"sync" | |
) | |
func main() { | |
var counter int | |
var routineCount = 100 | |
var wg sync.WaitGroup | |
wg.Add(routineCount) | |
for i := 0; i < routineCount; i++ { | |
go func() { | |
loc := counter | |
runtime.Gosched() | |
loc = loc + 1 | |
counter = loc | |
wg.Done() | |
}() | |
} | |
wg.Wait() | |
// Will not be equal to the number of Go routines that tried to increment counter | |
fmt.Println(counter) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment