Skip to content

Instantly share code, notes, and snippets.

@romanitalian
Last active April 26, 2018 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romanitalian/f403ceb6e492eaf6ba953cf67d5a22ff to your computer and use it in GitHub Desktop.
Save romanitalian/f403ceb6e492eaf6ba953cf67d5a22ff to your computer and use it in GitHub Desktop.
Why the result is not as expected with flag "-race"
package main
import (
"fmt"
"runtime"
"sync/atomic"
"time"
)
//$ go run -race main_atomic.go
//954203
//
//$ go run main_atomic.go
//1000000
type atomicCounter struct {
val int64
}
func (c *atomicCounter) Add(x int64) {
atomic.AddInt64(&c.val, x)
runtime.Gosched()
}
func (c *atomicCounter) Value() int64 {
return atomic.LoadInt64(&c.val)
}
func main() {
counter := atomicCounter{}
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