Last active
April 26, 2018 19:36
-
-
Save romanitalian/f403ceb6e492eaf6ba953cf67d5a22ff to your computer and use it in GitHub Desktop.
Why the result is not as expected with flag "-race"
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/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