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]

posted @ 2022-06-14 23:51  ty1539  阅读(46)  评论(0)    收藏  举报