方法一(对数据库的读写操作加锁)
一(DAO层加行锁:读写锁)
package main
import (
"sync"
)
//1、多个读之间不存在互斥关系
//2、写操作之间都是互斥的,并且写操作与读操作之间也都是互斥的
type idMutex map[string] *sync.RWMutex
var myIdMutex idMutex
func init() {
myIdMutex=make(map[string] *sync.RWMutex)
}
//读锁定
func (this *idMutex)RLock(id string){
m,ok:=(*this)[id]
if !ok {
m=new(sync.RWMutex)
(*this)[id]=m
}
m.RLock()
}
//读解锁
func (this *idMutex)RUnlock(id string){
m,ok:=(*this)[id]
if !ok {
return
}
m.RUnlock()
}
//写操作锁定
func (this *idMutex)Lock(id string){
m,ok:=(*this)[id]
if !ok {
m=new(sync.RWMutex)
(*this)[id]=m
}
m.Lock() //写操作锁定
}
//写操作解锁
func (this *idMutex)Unlock(id string) {
m,ok:=(*this)[id]
if !ok {
return
}
m.Unlock()//写操作解锁
}
type Accout struct {
Id string
}
//进行读的操作
func (this *Accout) Reed() {
myIdMutex.RLock(this.Id)
defer myIdMutex.RUnlock(this.Id)
}
//进行写的操作
func (this *Accout) Write() {
myIdMutex.Lock(this.Id) //写操作锁定
defer myIdMutex.Unlock(this.Id) //写操作解锁
}
func main() {
acout:=Accout{Id:"798456"}
acout.Reed()
acout.Write()
}
一(对象加锁) 将读写的方法封装,并且添加锁
type Accout struct {
flag sync.Mutex //sync.Mutex类型
}
//进行读的操作
func (a *Accout) Reed(n int) { //读
a.flag.Lock() //锁上
defer a.flag.Unlock() //在方法运行完之后解开
}
//进行写的操作
func (a *Accout) Write(n int) { //读
a.flag.Lock() //