The full code is here: https://play.golang.org/p/ggUoxtcv5m
go run -race main.go says that there is a race condition, which I can not explain. However, the program displays the correct end result.
Essence:
type SafeCounter struct {
c int
sync.Mutex
}
func (c *SafeCounter) Add() {
c.Lock()
c.c++
c.Unlock()
}
var counter *SafeCounter = &SafeCounter{}
use *SafeCounterin increment:
func incrementor(s string) {
for i := 0; i < 20; i++ {
x := counter
x.Add()
counter = x
}
}
The method is incrementorgenerated twice in main:
func main() {
go incrementor()
go incrementor()
}
So, as I said, go run -race main.goit will always say that a race has been discovered.
In addition, the end result is always correct (at least I ran this program several times, and it always says that the last counter is 40, which is correct). BUT, the program prints the wrong values at the beginning so you can get something like:
Incrementor1: 0 Counter: 2
Incrementor2: 0 Counter: 3
Incrementor2: 1 Counter: 4
// ang the rest is ok
1 .
- , , ?