Go使用sync.Map來解決map的并發(fā)操作問題
前言
在 Golang 中 map 不是并發(fā)安全的,自 1.9 才引入了 sync.Map ,sync.Map 的引入確實解決了 map 的并發(fā)安全問題,不過 sync.Map 卻沒有實現(xiàn) len() 函數(shù),如果想要計算 sync.Map 的長度,稍微有點麻煩,需要使用 Range 函數(shù)。
map 并發(fā)操作出現(xiàn)問題
func main() {
demo := make(map[int]int)
go func() {
for j := 0; j < 1000; j++ {
demo[j] = j
}
}()
go func() {
for j := 0; j < 1000; j++ {
fmt.Println(demo[j])
}
}()
time.Sleep(time.Second * 1)
}
執(zhí)行輸出:
fatal error: concurrent map read and map write
sync.Map 解決并發(fā)操作問題
func main() {
demo := sync.Map{}
go func() {
for j := 0; j < 1000; j++ {
demo.Store(j, j)
}
}()
go func() {
for j := 0; j < 1000; j++ {
fmt.Println(demo.Load(j))
}
}()
time.Sleep(time.Second * 1)
}
執(zhí)行輸出:
<nil> false
1 true...
999 true
計算 map 長度
func main() {
demo := make(map[int]int)
for j := 0; j < 1000; j++ {
demo[j] = j
}
fmt.Println("len of demo:", len(demo))
}
執(zhí)行輸出:
len of demo: 1000
計算 sync.Map 長度
func main() {
demo := sync.Map{}
for j := 0; j < 1000; j++ {
demo.Store(j, j)
}
lens := 0
demo.Range(func(key, value interface{}) bool {
lens++
return true
})
fmt.Println("len of demo:", lens)
}
執(zhí)行輸出:
len of demo: 1000
小結
- Load 加載 key 數(shù)據(jù)
- Store 更新或新增 key 數(shù)據(jù)
- Delete 刪除 key 數(shù)據(jù)
- Range 遍歷數(shù)據(jù)
- LoadOrStore 如果存在 key 數(shù)據(jù)則返回,反之則設置
- LoadAndDelete 如果存在 key 數(shù)據(jù)則刪除
到此這篇關于Go使用sync.Map來解決map的并發(fā)操作問題的文章就介紹到這了,更多相關Go sync.Map解決map并發(fā)操作內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
go select編譯期的優(yōu)化處理邏輯使用場景分析
select 是 Go 中的一個控制結構,類似于用于通信的 switch 語句。每個 case 必須是一個通信操作,要么是發(fā)送要么是接收。接下來通過本文給大家介紹go select編譯期的優(yōu)化處理邏輯使用場景分析,感興趣的朋友一起看看吧2021-06-06
golang字符串拼接實現(xiàn)方式和區(qū)別對比
本文介紹了Go語言中字符串拼接的多種方法及其優(yōu)缺點,推薦使用strings.Builder進行頻繁拼接以優(yōu)化內存分配和性能,同時,還討論了通過sync.Pool優(yōu)化高頻創(chuàng)建的對象,以減少垃圾回收壓力,感興趣的朋友一起看看吧2025-02-02

