亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

圍棋比賽條件改變

圍棋比賽條件改變

Go
泛舟湖上清波郎朗 2021-04-09 19:15:59
《 Go in action》關于比賽條件的樣本: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)    }}據說最終計數器的末尾應為2,解釋如下:“每個goroutine都會覆蓋另一個工作。這在goroutine交換發生時會發生。每個goroutine都會制作自己的counter變量副本,然后進行交換當該goroutine有時間再次執行時,counter變量的值已更改,但goroutine不會更新其副本,而是繼續增加其擁有的副本并將其值重新設置為計數器變量,替換了其他goroutine執行的工作?!蔽蚁脒@是環境原因,我的機器輸出4為1.10.3 + win10。我想知道自本書發行以來發生了什么變化?如果我取消注釋1,則最終計數器將打印2;如果我取消注釋2,則將隨機打印2。為什么?
查看完整描述

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

$


查看完整回答
反對 回復 2021-04-19
  • 1 回答
  • 0 關注
  • 269 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號