3 回答

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

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

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()
}
- 3 回答
- 0 關(guān)注
- 121 瀏覽
添加回答
舉報(bào)