1 回答

TA貢獻1784條經驗 獲得超7個贊
是的,有許多Go習語可以使用 - 以防止數據競爭 - 并且在沒有正確同步的情況下不應該并發寫入變量(或并發讀寫):
對于您的特殊情況 - 寫入相同的值。用:sync.Once
type simpleTx struct {
sync.Once
gas uint64
}
func (tx *simpleTx) UpdateGas() {
tx.Do(func() { tx.gas = 125 })
}
用于原子寫入:atomic.StoreUint64
atomic.StoreUint64(&tx.gas, 125)
用:sync.Mutex
type simpleTx struct {
sync.Mutex
gas uint64
}
func (tx *simpleTx) UpdateGas() {
tx.Lock()
tx.gas = 125
tx.Unlock()
}
使用通道:
type simpleTx struct {
gas chan uint64
}
func (tx *simpleTx) UpdateGas() {
select {
case tx.gas <- 125:
default:
}
}
func TestUpdateGas(t *testing.T) {
var wg sync.WaitGroup
tx := &simpleTx{make(chan uint64, 1)}
for i := 0; i < 100; i++ {
wg.Add(1)
go func(t *simpleTx) {
tx.UpdateGas()
wg.Done()
}(tx)
}
wg.Wait()
}
- 1 回答
- 0 關注
- 105 瀏覽
添加回答
舉報