• 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

  • 相关阅读:
    day12. 闭包
    day11.函数的全局变量和局部变量
    day10.函数基础及函数参数
    day9.关于文件的操作
    day7.关于字符串的相关操作
    day8.列表、字典、集合相关操作
    day6. while双项循环及for循环
    LeetCode-Unique Binary Search Trees II
    LeetCode-Unique Binary Search Trees
    LeetCode-Edit Distance
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/15873817.html
Copyright © 2020-2023  润新知