Created
April 28, 2018 10:43
-
-
Save romanitalian/4b55a3d077c29d9030e591aa81c00c47 to your computer and use it in GitHub Desktop.
Fix race with flag "-race" by using sync.WaitGroup
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" | |
"sync/atomic" | |
"time" | |
) | |
// $ go run main_waitgroup.go | |
//1000000 | |
//$ go run -race main_waitgroup.go | |
//1000000 | |
type atomicCounterWg struct { | |
val int64 | |
} | |
func (c *atomicCounterWg) Add(x int64) { | |
atomic.AddInt64(&c.val, x) | |
runtime.Gosched() | |
} | |
func (c *atomicCounterWg) Value() int64 { | |
return atomic.LoadInt64(&c.val) | |
} | |
func main() { | |
counter := atomicCounterWg{} | |
var wg sync.WaitGroup | |
for i := 0; i < 100; i++ { | |
wg.Add(1) | |
go func(no int) { | |
for i := 0; i < 10000; i++ { | |
counter.Add(1) | |
} | |
wg.Done() | |
}(i) | |
} | |
time.Sleep(time.Second) | |
wg.Wait() | |
fmt.Println(counter.Value()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment