【发布时间】:2021-05-17 01:23:57
【问题描述】:
type simpleTx struct {
gas uint64
}
func (tx *simpleTx) UpdateGas() {
tx.gas = 125
}
func TestUpdateGas(t *testing.T) {
var wg sync.WaitGroup
wg.Add(100)
tx := &simpleTx{}
for i:=0; i <100; i++ {
go func(t *simpleTx)() {
tx.UpdateGas()
wg.Done()
}(tx)
}
wg.Wait()
}
使用-race 选项运行时,上述测试会打印出“WARNING:DATA RACE”。
golang 中是否有任何类型可用于具有相同值的并发写入?
我需要始终使用互斥锁或原子变量吗?
【问题讨论】:
-
golang 中是否有任何类型可以用于并发写入相同的值? 没有。我需要始终使用互斥锁或原子变量吗? i> 是的。
-
并发写入相同的值是未定义的行为。了解
sync.Once可能会有所帮助,它允许您多次调用同一个函数,但只执行一次。
标签: go concurrency