Skip to content

Instantly share code, notes, and snippets.

@mannion007
Created February 27, 2020 21:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mannion007/190ac9da645e885638400a28b166a443 to your computer and use it in GitHub Desktop.
Save mannion007/190ac9da645e885638400a28b166a443 to your computer and use it in GitHub Desktop.
Go Race condition
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