1 回答

TA貢獻1757條經驗 獲得超7個贊
這本書是錯的。關于數據爭用的要點是結果不確定。
例如,Final Counter可以是任何值。
package main
import (
"fmt"
"runtime"
"sync"
)
var (
counter int
wg sync.WaitGroup
)
func main() {
wg.Add(2)
go incCounter(1)
go incCounter(2)
wg.Wait()
fmt.Println("Final Counter:", counter)
}
func incCounter(id int) {
defer wg.Done()
for count := 0; count < 2; count++ {
value := counter
//1 fmt.Println("value=",value)
runtime.Gosched()
value++
counter = value
//2 fmt.Println("counter=",counter)
}
}
輸出:
$ go version
go version devel +65fa2b615b Fri Aug 3 23:35:53 2018 +0000 linux/amd64
$ go run racer.go
Final Counter: 4
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 4
$ go run racer.go
Final Counter: 2
$ go run racer.go
Final Counter: 4
$ go run -race racer.go
==================
WARNING: DATA RACE
Read at 0x0000005e4600 by goroutine 7:
main.incCounter()
/home/peter/gopath/src/racer.go:27 +0x6f
Previous write at 0x0000005e4600 by goroutine 6:
main.incCounter()
/home/peter/gopath/src/racer.go:33 +0x90
Goroutine 7 (running) created at:
main.main()
/home/peter/gopath/src/racer.go:17 +0x89
Goroutine 6 (finished) created at:
main.main()
/home/peter/gopath/src/racer.go:16 +0x68
==================
Final Counter: 4
Found 1 data race(s)
exit status 66
$
- 1 回答
- 0 關注
- 269 瀏覽
添加回答
舉報