第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

Go
慕桂英546537 2022-06-27 10:00:27
下面的代碼每次執(zhí)行后都會打印不同的值,但我希望這些值相同,如何在不使用的情況下更改下面的代碼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貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊

你有一個(gè)數(shù)據(jù)競賽,結(jié)果是不確定的。您必須同步對共享變量的訪問:


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訪問/修改變量。


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

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超4個(gè)贊

已經(jīng)提到您有“數(shù)據(jù)競賽”,使用Mutex是一種解決方案?;蛘撸梢允褂胊tomic更快的包。


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())

}


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

TA貢獻(xiàn)2036條經(jīng)驗(yàn) 獲得超8個(gè)贊

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


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


并將其用于inc :


func inc(num int) {

    mu.Lock()

    defer mu.Unlock()

    total += num

    wg.Done()

}


查看完整回答
反對 回復(fù) 2022-06-27
  • 3 回答
  • 0 關(guān)注
  • 121 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號