Skip to content

Instantly share code, notes, and snippets.

@kaipyroami
Created September 4, 2019 16:32
Show Gist options
  • Save kaipyroami/83de0ee0f0bf2426399131ba3c1d4d40 to your computer and use it in GitHub Desktop.
Save kaipyroami/83de0ee0f0bf2426399131ba3c1d4d40 to your computer and use it in GitHub Desktop.
Just a simple example of a mutex during race condition.
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