亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang 并發寫入具有相同值的 uint64 變量?

golang 并發寫入具有相同值的 uint64 變量?

Go
慕哥9229398 2022-08-30 21:40:04
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()}上面的測試打印出“警告:數據競賽”,當運行選項。golang中是否有任何類型可用于具有相同值的并發寫入?我需要始終使用互斥體還是原子變量?-race
查看完整描述

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

}


查看完整回答
反對 回復 2022-08-30
  • 1 回答
  • 0 關注
  • 105 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號