###互斥锁
其中Mutex为互斥锁,Lock()加锁,Unlock()解锁,使用Lock()加锁后,便不能再次对其进行加锁,直到利用Unlock()解锁对其解锁后,才能再次加锁.适用于读写不确定场景,即读写次数没有明显的区别,并且只允许只有一个读或者写的场景,所以该锁叶叫做全局锁.
package main
import (
"fmt"
"sync"
"errors"
)
type MyMap struct {
mp map[string]int
mutex *sync.Mutex
}
func (this *MyMap) Get(key string) (int, error) {
this.mutex.Lock()
i, ok := this.mp[key]
this.mutex.Unlock()
if !ok {
return i, errors.New("不存在")
}
return i, nil
}
func (this *MyMap) Set(key string, v int) {
this.mutex.Lock()
defer this.mutex.Unlock()
this.mp[key] = v
}
func (this *MyMap) Display() {
this.mutex.Lock