Created
September 4, 2019 16:32
-
-
Save kaipyroami/83de0ee0f0bf2426399131ba3c1d4d40 to your computer and use it in GitHub Desktop.
Just a simple example of a mutex during 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 wg sync.WaitGroup | |
c := 0 | |
wg.Add(100) | |
var mux sync.Mutex | |
for i := 0; i < 100; i++ { | |
go func() { | |
mux.Lock() | |
count := c | |
runtime.Gosched() | |
count++ | |
c = count | |
fmt.Println(c) | |
wg.Done() | |
mux.Unlock() | |
}() | |
} | |
wg.Wait() | |
fmt.Println("End value: ", c) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment