這個問題在這里已經有了答案: 并發讀/寫操作的 Golang 映射有多安全? (8 個回答) 8 小時前關閉。
這是我正在嘗試做的簡化版本。
我有以下地圖m := make(map[int][]string)。這張地圖將被多個 goroutines 訪問......但是......
每個 goroutine 只會訪問 map 的一個元素。例如 goroutine g1 只會訪問 m[1] 處的切片。Goroutine g2 只會訪問 m[2] 等等。
goroutine 將同時讀取和寫入每個 map 元素中的切片。
我的問題是,我需要同步訪問地圖嗎?
uj5u.com熱心網友回復:
是的,無論如何你都必須這樣做。
var mu sync.Mutex
mu.Lock()
// access to map
mu.Unlock()
更新:因為在幕后, map 是指向hmap struct的指標:
type hmap struct {
count int // # live cells == size of map. Must be first (used by len() builtin)
flags uint8
B uint8 // log_2 of # of buckets (can hold up to loadFactor * 2^B items)
noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details
hash0 uint32 // hash seed
buckets unsafe.Pointer // array of 2^B Buckets. may be nil if count==0.
oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing
nevacuate uintptr // progress counter for evacuation (buckets less than this have been evacuated)
extra *mapextra // optional fields
}
如果你的 goroutines 可以同時訪問記憶體中的這個結構,那么當幾個例程同時更改這個結構時,你就會遇到競爭條件。
例如,兩個 goroutine 同時向 map 添加新資料。第一個 goroutine 將大小增加 1,然后大小變為 3。第二個 goroutine 也將大小增加 1,但它不知道大小已經是 3。
結果,結構的大小將是 3,而不是應有的 4。
請按照以下方式思考。映射中的每個鍵和值在記憶體中彼此分開。但整張地圖有一個共同的標題。當地圖改變時,這個標題也會改變。因此,需要互斥體。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/466883.html
上一篇:GoLang并發-從不呼叫主程式
