golang mysql 高并发_golang 高并发数据库库存同步处理

方法一(对数据库的读写操作加锁)

一(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() //

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值