Created
July 3, 2024 19:23
-
-
Save joundy/8098b4e61e7d50d876e9b79164c7770c to your computer and use it in GitHub Desktop.
Golang race condition example
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" | |
| "runtime" | |
| "sync" | |
| ) | |
| type SC struct { | |
| m sync.Mutex | |
| v int | |
| } | |
| func main() { | |
| runtime.GOMAXPROCS(2) | |
| for i := 0; i < 10; i++ { | |
| sc := SC{v: 0} | |
| var wg sync.WaitGroup | |
| gr := 20 | |
| wg.Add(gr) | |
| for i := 0; i < gr; i++ { | |
| go func(c *SC) { | |
| for i := 0; i < 10000; i++ { | |
| // to prevent a race condition, it's necessary to use a locking | |
| // mechanism when the data is shared across goroutines. | |
| // try to run this with/without "lock" to see the race condition: go run -race main.go | |
| // c.m.Lock() | |
| c.v++ | |
| // c.m.Unlock() | |
| } | |
| wg.Done() | |
| }(&sc) | |
| } | |
| wg.Wait() | |
| fmt.Println(sc.v) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment