Skip to content

Instantly share code, notes, and snippets.

@romanitalian
Last active April 28, 2018 10:45
Show Gist options
  • Save romanitalian/41f727e3d1313055c44fbb01120b3119 to your computer and use it in GitHub Desktop.
Save romanitalian/41f727e3d1313055c44fbb01120b3119 to your computer and use it in GitHub Desktop.
Why the result is not as expected with flag "-race"
package main
import (
"sync"
"time"
"fmt"
)
//$ go run -race main_mutex.go
//610917
//
//$ go run main_mutex.go
//1000000
// This gist was made from StackOverflow the answer: https://stackoverflow.com/questions/50050755/why-the-result-is-not-as-expected-with-flag-race/50051808#50051808
type mutexCounter struct {
mu sync.Mutex
x int64
}
func (c *mutexCounter) Add(x int64) {
c.mu.Lock()
c.x += x
c.mu.Unlock()
}
func (c *mutexCounter) Value() (x int64) {
c.mu.Lock()
x = c.x
c.mu.Unlock()
return
}
func main() {
counter := mutexCounter{}
for i := 0; i < 100; i++ {
go func(no int) {
for i := 0; i < 10000; i++ {
counter.Add(1)
}
}(i)
}
time.Sleep(time.Second)
fmt.Println(counter.Value())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment