Created
April 13, 2023 21:40
-
-
Save Hypro999/c3a3f04b4940c4a2805974d020b0b0eb to your computer and use it in GitHub Desktop.
Small and simple example demonstrating a race condition. Intended to introduce newcomers to the world of concurrency problems.
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" | |
"sync" | |
) | |
func demoRace() { | |
race := func() int { | |
i := -1 | |
var wg sync.WaitGroup | |
wg.Add(2) | |
// Race contestant 1 | |
go func() { | |
i = 0 | |
wg.Done() | |
}() | |
// Race contestant 2 | |
go func() { | |
i = 1 | |
wg.Done() | |
}() | |
wg.Wait() | |
return i | |
} | |
n := 1000 | |
cnts := []int{0, 0} | |
for n > 0 { | |
res := race() | |
cnts[res]++ | |
n-- | |
} | |
fmt.Println(cnts) | |
} | |
func main() { | |
demoRace() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment