Go sync.Map

Posted jihite

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Go sync.Map相关的知识,希望对你有一定的参考价值。

需求

读写共享map

 

#1 常规map

package main

import (
    "fmt"
    "strconv"
    "sync"
)


func _110Test1() 
    wg := sync.WaitGroup
    mp := make(map[string]int)
    for i := 0; i < 20; i++ 
        wg.Add(1)
        go func(n int) 
            key := strconv.Itoa(n)
            mp[key] = n
            value, ok := mp[key]
            fmt.Println("key:%v, value:%v, ok:%v", key, value, ok)
            wg.Done()
        (i)
    
    wg.Wait()


func main() 
    _110Test1()

执行:

fatal error: concurrent map writes

问题:内置的map不是并发安全的,要为map加锁来保证并发的安全性了

 

#2开箱即用包:sync.Map()

特点:开箱即用且并发安全

package main

import (
    "fmt"
    "strconv"
    "sync"
)

var m = sync.Map

func _110Test2() 
    wg := sync.WaitGroup
    for i := 0; i < 20; i++ 
        wg.Add(1)
        go func(n int) 
            key := strconv.Itoa(n)
            m.Store(key, n)
            value, ok := m.Load(key)
            fmt.Printf("key:%v, value:%v, ok:%v\\n", key, value, ok)
            wg.Done()
        (i)
    
    wg.Wait()


func main() 
    _110Test2()

执行:

key:19, value:19, ok:true
key:0, value:0, ok:true
key:14, value:14, ok:true
key:16, value:16, ok:true
key:17, value:17, ok:true
key:18, value:18, ok:true
key:2, value:2, ok:true
key:1, value:1, ok:true
key:11, value:11, ok:true
key:15, value:15, ok:true
key:3, value:3, ok:true
key:10, value:10, ok:true
key:12, value:12, ok:true
key:5, value:5, ok:true
key:13, value:13, ok:true
key:6, value:6, ok:true
key:9, value:9, ok:true
key:7, value:7, ok:true
key:8, value:8, ok:true
key:4, value:4, ok:true

 

以上是关于Go sync.Map的主要内容,如果未能解决你的问题,请参考以下文章

Go36-34,35-并发安全字典(sync.Map)

Go 实现线程安全 map 读写(sync.RWMutex)

go sync.map的使用

go - 更为安全的使用 sync.Map 组件

深度解密 Go 语言之 sync.map

sync.Map源码分析