go 自定义RWMutex
作者:互联网
package main
import (
"fmt"
"strconv"
"sync"
)
type RwMap struct{
mu sync.RWMutex
data map[string]int
}
func New() *RwMap {
return &RwMap{data: make(map[string]int)}
}
func (r *RwMap )Read(key string)int {
r.mu.RLock()
defer r.mu.RUnlock()
return r.data[key]
}
func (r *RwMap)Write(wg *sync.WaitGroup, key string, val int) {
defer wg.Done()
r.mu.Lock()
defer r.mu.Unlock()
r.data[key] = val
}
func main() {
rwMap := New()
wg := sync.WaitGroup{ }
wg.Add(10)
for i :=0; i < 10; i ++ {
go rwMap.Write(&wg, strconv.Itoa(i), i)
}
wg.Wait()
fmt.Println(rwMap.data)
}
输出:
map[0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7 8:8 9:9]
标签:wg,RWMutex,自定义,int,mu,RwMap,key,go,data 来源: https://www.cnblogs.com/heris/p/16376888.html