golang是否使用相同的值并发写入uint64变量?
以上测试打印出警告:使用-RACE选项运行时数据竞争。 golang中是否有任何类型可用于具有相同值的并发写入?golang是否使用相同的值并发写入uint64变量?,go,concurrency,Go,Concurrency,以上测试打印出警告:使用-RACE选项运行时数据竞争。 golang中是否有任何类型可用于具有相同值的并发写入? 我是否需要始终使用互斥或原子变量?是的,有许多Go习惯用法可供使用-以防止数据竞争-不应在没有适当同步的情况下并发写入变量或并发读写: 对于您的特殊情况-编写相同的值。使用同步。一次: 将atomic.StoreUint64用于原子写入: 使用sync.Mutex: 使用频道: golang中是否有任何类型可用于具有相同值的并发写入?不需要。我是否需要始终使用互斥或原子变量?是。对相
我是否需要始终使用互斥或原子变量?是的,有许多Go习惯用法可供使用-以防止数据竞争-不应在没有适当同步的情况下并发写入变量或并发读写: 对于您的特殊情况-编写相同的值。使用同步。一次: 将atomic.StoreUint64用于原子写入: 使用sync.Mutex: 使用频道:
golang中是否有任何类型可用于具有相同值的并发写入?不需要。我是否需要始终使用互斥或原子变量?是。对相同值的并发写入是未定义的行为。这可能有助于了解,它允许您多次调用同一个函数,但只能执行一次。
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()
}
type simpleTx struct {
sync.Once
gas uint64
}
func (tx *simpleTx) UpdateGas() {
tx.Do(func() { tx.gas = 125 })
}
atomic.StoreUint64(&tx.gas, 125)
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()
}