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

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

帶有sync.waitGroup的Goroutine每次輸出不同的值

帶有sync.waitGroup的Goroutine每次輸出不同的值

Go
慕桂英546537 2022-06-27 10:00:27
下面的代碼每次執行后都會打印不同的值,但我希望這些值相同,如何在不使用的情況下更改下面的代碼time.Sleeppackage mainimport (    "fmt"    "sync")var total intvar wg sync.WaitGroup// Inc increments the counter for the given key.func inc(num int) {    total += num    wg.Done()}// Value returns the current value of the counter for the given key.func getValue() int {    return total}func main() {    for i := 1; i <= 1000; i++ {        wg.Add(1)        go inc(i)    }    wg.Wait()    fmt.Println(getValue())}
查看完整描述

3 回答

?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

你有一個數據競賽,結果是不確定的。您必須同步對共享變量的訪問:


var total int

var lock sync.Mutex

var wg sync.WaitGroup


// Inc increments the counter for the given key.

func inc(num int) {

    lock.Lock()

    defer lock.Unlock()

    total += num

    wg.Done()

}


// Value returns the current value of the counter for the given key.

func getValue() int {

    lock.Lock()

    defer lock.Unlock()

    return total

}

或者,用于sync/atomic訪問/修改變量。


查看完整回答
反對 回復 2022-06-27
?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

已經提到您有“數據競賽”,使用Mutex是一種解決方案?;蛘?,您可以使用atomic更快的包。


package main


import (

    "fmt"

    "sync"

    "sync/atomic"

)


var total uint64

var wg sync.WaitGroup


func inc(num uint64) {

    atomic.AddUint64(&total, 1)

    wg.Done()

}


// Value returns the current value of the counter for the given key.

func getValue() uint64 {

    return atomic.LoadUint64(&total)

}


func main() {

    for i := uint64(1); i <= 1000; i++ {

        wg.Add(1)

        go inc(i)

    }

    wg.Wait()

    fmt.Println(getValue())

}


查看完整回答
反對 回復 2022-06-27
?
慕桂英3389331

TA貢獻2036條經驗 獲得超8個贊

每次獲得不同值的原因是total += num.


一個簡單的解決方法是添加互斥鎖: var mu sync.Mutex


并將其用于inc :


func inc(num int) {

    mu.Lock()

    defer mu.Unlock()

    total += num

    wg.Done()

}


查看完整回答
反對 回復 2022-06-27
  • 3 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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