Skip to content

Instantly share code, notes, and snippets.

@Hypro999
Created April 13, 2023 21:40
Show Gist options
  • Save Hypro999/c3a3f04b4940c4a2805974d020b0b0eb to your computer and use it in GitHub Desktop.
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.
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