快速解決Golang Map 併發讀寫安全的問題
一、錯誤案例
package main import ( "fmt" "time" ) var TestMap map[string]string func init() { TestMap = make(map[string]string,1) } func main() { for i := 0; i < 1000; i++ { go Write("aaa") go Read("aaa") go Write("bbb") go Read("bbb") } time.Sleep(5 * time.Second) } func Read(key string) { fmt.Println(TestMap[key]) } func Write(key string) { TestMap[key] = key }
上面程式碼執行大概率出現報錯:fatal error: concurrent map writes
二、問題分析
網上關於 golang 程式設計中 map 併發讀寫相關的資料很多,但總是都說成 併發讀寫 造成上面的錯誤,到底是 併發讀 還是 併發寫 造成的,這個很多資料都沒有說明。
我們把上面的案例分別在迴圈中註釋 Read 和 Write 函式的呼叫,分別測試 併發讀 和 併發寫;
迴圈次數分別測試了 100、1 w、100 w 次,併發讀操作絕對不會報上面的錯,而併發寫基本都會報錯。
因此,這個錯誤主要原因是:map 併發寫。
三、問題原因
為什麼 map 併發寫會導致這個錯誤? 網路上的相關文章也大都有說明。
因為 map 變數為 指標型別變數,併發寫時,多個協程同時操作一個記憶體,類似於多執行緒操作同一個資源會發生競爭關係,共享資源會遭到破壞,因此golang 出於安全的考慮,丟擲致命錯誤:fatal error: concurrent map writes。
四、解決方案
網上各路資料解決方案較多,主要思路是通過加鎖保證每個協程同步操作記憶體。
github 上找到一個 concurrentMap 包,案例程式碼修改如下:
package main import ( "fmt" cmap "github.com/orcaman/concurrent-map" "time" ) var TestMap cmap.ConcurrentMap func init() { TestMap = cmap.New() } func main() { for i := 0; i < 100; i++ { go Write("aaa","111") go Read("aaa") go Write("bbb","222") go Read("bbb") } time.Sleep(5 * time.Second) } func Read(key string) { if v,ok := TestMap.Get(key); ok { fmt.Printf("鍵值為 %s 的值為:%s",key,v) } else { fmt.Printf("鍵值不存在") } } func Write(key string,value string) { TestMap.Set(key,value) }
五、思考總結
因為我是以 PHP 開啟的程式設計世界,PHP 語言只有單執行緒,且不涉及指標操作,變數型別也是弱變數,以 PHP 程式設計思維剛開始接觸 Golang 時還比較容易上手,但越往後,語言的特性區別就體現得越來越明顯,思維轉變就越來越大,對我來說是打開了一個新世界。
像本文出現的錯誤案例,也是因為自己沒有多執行緒程式設計的思維基礎,導致對這種問題不敏感,還是花了蠻多時間理解的。希望對和我有相似學習路線的朋友提供到一些幫助。
補充:Golang Map併發處理機制(sync.Map)
Go語言中的Map在併發情況下,只讀是執行緒安全的,同時讀寫執行緒不安全。
示例:
package main import ( "fmt" ) var m = make(map[int]int) func main() { //寫入操作 i:=0 go func() { for{ i++ m[1]=i } }() //讀操作 go func() { for{ fmt.Println(m[1]) } }() //無限迴圈,讓併發程式在後臺執行 for { ; } }
從以上示例可以看出,不斷地對map進行讀和寫,會出現錯誤。主要原因是對map進行讀和寫發生了競態問題。map內部會對這種併發操作進行檢查並提前發現。
如果確實需要對map進行併發讀寫操作,可以採用加鎖機制、channel同步機制,但這樣效能並不高。
Go語言在1.9版本中提供了一種效率較高的併發安全的sync.Map。
sync.Map結構如下:
The zero Map is empty and ready for use. A Map must not be copied after first use. type Map struct { mu Mutex misses int } // Load returns the value stored in the map for a key,or nil if no // value is present. // The ok result indicates whether value was found in the map. func (m *Map) Load(key interface{}) (value interface{},ok bool) { } // Store sets the value for a key. func (m *Map) Store(key,value interface{}) { } // LoadOrStore returns the existing value for the key if present. // Otherwise,it stores and returns the given value. // The loaded result is true if the value was loaded,false if stored. func (m *Map) LoadOrStore(key,value interface{}) (actual interface{},loaded bool) { } // Delete deletes the value for a key. func (m *Map) Delete(key interface{}) { } // Range calls f sequentially for each key and value present in the map. // If f returns false,range stops the iteration. // // Range does not necessarily correspond to any consistent snapshot of the Map's // contents: no key will be visited more than once,but if the value for any key // is stored or deleted concurrently,Range may reflect any mapping for that key // from any point during the Range call. // // Range may be O(N) with the number of elements in the map even if f returns // false after a constant number of calls. func (m *Map) Range(f func(key,value interface{}) bool) { } func (m *Map) missLocked() { } func (m *Map) dirtyLocked() { }
其實,sync.Map內部還是進行了加鎖機制,不過進行了一定的優化。
sync.Map使用示例:
package main import ( "fmt" "sync" "time" ) var m1 sync.Map func main() { i := 0 go func() { for { i++ m1.Store(1,i) time.Sleep(1000) } }() go func() { for{ time.Sleep(1000) fmt.Println(m1.Load(1)) } }() for { ; } }
成功執行效果如下:
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。