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

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

更改地圖鏈接是否并發安全?

更改地圖鏈接是否并發安全?

Go
三國紛爭 2022-06-21 15:47:44
您知道嗎,在并發環境中將映射變量鏈接更改為另一個是否安全?一個例子是在一個 goroutine 中將 mapdata替換為新的 map,并在另一個 goroutine 中從它們中讀取元素:import (    "fmt"    "math/rand"    "strconv"    "testing"    "time")func TestMap(t *testing.T) {    s1 := rand.NewSource(time.Now().UnixNano())    r1 := rand.New(s1)    data := fill(r1.Intn(100))    timer := time.NewTimer(10 * time.Second)    go func() {        s1 := rand.NewSource(time.Now().UnixNano())        r1 := rand.New(s1)        for {            select {            case <-timer.C:                return            default:            }            p := r1.Intn(100)            v := fill(p)            data = v            fmt.Println("_p=" + strconv.Itoa(p))        }    }()    for range []int{1, 2, 3, 4, 5, 6, 7, 8} {        go func() {            s1 := rand.NewSource(time.Now().UnixNano())            r1 := rand.New(s1)            for {                select {                case <-timer.C:                    return                default:                }                n := r1.Intn(100)                s := strconv.Itoa(n)                fmt.Println(data[s])            }        }()    }    <-timer.C}func fill(postfix int) map[string][]string {    m := make(map[string][]string)    for i := 0; i < 100; i++ {        s := strconv.Itoa(i)        m[s] = []string{s + "_" + strconv.Itoa(postfix)}    }    return m}
查看完整描述

2 回答

?
侃侃爾雅

TA貢獻1801條經驗 獲得超16個贊

當然,這并不安全。沒有任何變量(包括映射)對于并發讀寫是安全的。

您的一個 goroutine 寫入data,另一個讀取它。運行測試go test -race還會報告數據競爭:

testing.go:954: race detected during execution of test

您必須從多個 goroutine 同步讀取和寫入data變量。


查看完整回答
反對 回復 2022-06-21
?
蕭十郎

TA貢獻1815條經驗 獲得超13個贊

不是的,更新數據時使用sync.Mutex 鎖定并解鎖。



查看完整回答
反對 回復 2022-06-21
  • 2 回答
  • 0 關注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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