是的,有许多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()
}