golang 自带的map不是并发安全的,并发读写会报错:
fatal error: concurrent map read and map write一般的解决方式是加锁,控制互斥。
1.加锁的map如下代码所示:
package main
import (
    "fmt"
    "sync"
    "time"
)
type Map struct {
    m map[int]int
    sync.RWMutex
}
func(this *Map) Get(key int) int {
    this.RLock()
    defer this.RUnlock()
    
    v := this.m[i]
    return v
}
func(this *Map) Set(k, v int) {
    this.Lock()
    defer this.Unlock()
    
    this.m[k] = v
}
func main(){
    newMap := &Map{m: make(map[int]int)}
    
    for i := 0; i< 10000; i<++ {
        go newMap.Set(i, i)
    }
    
    for i := 0; i< 10000; i<++ {
        go fmt.Println(i, newMap.Get(i))
    }
    
    time.Sleep(time.Second)
}
syncsync.Map使用举例如下:
StoreLoadDeletepackage main
import (
        "fmt"
        "sync"
)
type Counter struct {
        count int
}
func main() {
        var m sync.Map
        m.Store("a", 1)
        m.Store("b", 2)
        counter := &Counter{count:2}
        m.Store("c", counter)
        fmt.Println("m:", m)
        v, ok := m.Load("a")
        fmt.Println("a v:", v, ", ok:", ok)
        fmt.Printf("a type: %T\n", v)
        v, ok = m.Load("b")
        fmt.Println("b v:", v, ", ok:", ok)
        v, ok = m.Load("c")
        fmt.Println("c v:", v, ", ok:", ok)
        fmt.Printf("c type %T\n", v)
        vc,_ := v.(*Counter)
        vc.count += 1
        fmt.Println("================")
        v, ok = m.Load("c")
        fmt.Println("c v:", v, ", ok:", ok)
        m.Delete("d")
}
output:
3.参考m: {{0 0} {{map[] true}} map[a:0xc00000e028 b:0xc00000e030 c:0xc00000e038] 0}
a v: 1 , ok: true
a type: int
b v: 2 , ok: true
c v: &{2} , ok: true
c type *main.Counter
================
c v: &{3} , ok: true
