侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

golang线程安全的map实现

Go  /  管理员 发布于 7年前   341

网上找的协程安全的map都是用互斥锁或者读写锁实现的,这里用单个协程来实现下,即所有的增删查改操作都集成到一个goroutine中,这样肯定不会出现多线程并发访问的问题。

基本思路是后台启动一个长期运行的goroutine,阻塞的接受自己channel中的请求req,req分为不同的请求,比如读key,写key等,然后在这个goroutine中进行各种操作。

例: Get方法向readSig(channel)中发送一条请求。请求是readReq的指针,当run方法接收到信号时,读取底层map,将值写入readReq的value中(value是个channel),Get方法阻塞的接收value,接收到就返回value。

ps:花了两个多小时写完,只是简单的做了测试,没有深入测试,另外性能也没有测过,以后有空会深入测试一下正确性以及相比加锁的写法其性能如何。

package util type smap struct { m      map[interface{}]interface{} readSig   chan *readReq writeSig   chan *writeReq lenSig    chan *lenReq terminateSig chan bool delSig    chan *delReq scanSig   chan *scanReq} type readReq struct { key  interface{} value interface{} ok  chan bool} type writeReq struct { key  interface{} value interface{} ok  chan bool} type lenReq struct { len chan int} type delReq struct { key interface{} ok chan bool} type scanReq struct { do     func(interface{}, interface{}) doWithBreak func(interface{}, interface{}) bool brea    int done    chan bool}// NewSmap returns an instance of the pointer of safemapfunc NewSmap() *smap { var mp smap mp.m = make(map[interface{}]interface{}) mp.readSig = make(chan *readReq) mp.writeSig = make(chan *writeReq) mp.lenSig = make(chan *lenReq) mp.delSig = make(chan *delReq) mp.scanSig = make(chan *scanReq) go mp.run() return &mp} //background function to operate map in one goroutine//this can ensure that the map is Concurrent security.func (s *smap) run() { for { select { case read := <-s.readSig:  if value, ok := s.m[read.key]; ok {  read.value = value  read.ok <- true  } else {  read.ok <- false  } case write := <-s.writeSig:  s.m[write.key] = write.value  write.ok <- true case l := <-s.lenSig:  l.len <- len(s.m) case sc := <-s.scanSig:  if sc.brea == 0 {  for k, v := range s.m {   sc.do(k, v)  }  } else {  for k, v := range s.m {   ret := sc.doWithBreak(k, v)   if ret {   break   }  }  }  sc.done <- true case d := <-s.delSig:  delete(s.m, d.key)  d.ok <- true case <-s.terminateSig:  return } }} //Get returns the value of key which provided.//if the key not found in map, ok will be false.func (s *smap) Get(key interface{}) (interface{}, bool) { req := &readReq{ key: key, ok: make(chan bool), } s.readSig <- req ok := <-req.ok return req.value, ok} //Set set the key and value to map//ok returns true indicates that key and value is successfully added to mapfunc (s *smap) Set(key interface{}, value interface{}) bool { req := &writeReq{ key:  key, value: value, ok:  make(chan bool), } s.writeSig <- req return <-req.ok //TODO 暂时先是同步的,异步的可能存在使用方面的问题。} //Clear clears all the key and value in map.func (s *smap) Clear() { s.m = make(map[interface{}]interface{})} //Size returns the size of map.func (s *smap) Size() int { req := &lenReq{ len: make(chan int), } s.lenSig <- req return <-req.len} //terminate s.Run function. this function is usually called for debug.//after this do NOT use smap again, because it can make your program block.func (s *smap) TerminateBackGoroutine() { s.terminateSig <- true} //Del delete the key in mapfunc (s *smap) Del(key interface{}) bool { req := &delReq{ key: key, ok: make(chan bool), } s.delSig <- req return <-req.ok} //scan the map. do is a function which operate all of the key and value in mapfunc (s *smap) EachItem(do func(interface{}, interface{})) { req := &scanReq{ do:  do, brea: 0, done: make(chan bool), } s.scanSig <- req <-req.done} //scan the map util function 'do' returns true. do is a function which operate all of the key and value in mapfunc (s *smap) EachItemBreak(do func(interface{}, interface{}) bool, condition bool) { req := &scanReq{ doWithBreak: do, brea:    1, done:    make(chan bool), } s.scanSig <- req <-req.done} //Exists checks whether the key which provided is exists in mapfunc (s *smap) Exists(key interface{}) bool { if _,found := s.Get(key); found { return true } return false}

github地址:https://github.com/hackssssss/safemap

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    Golang实现对map的并发读写的方法示例
    下一条:
    golang高并发的深入理解
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2017-09
    • 2020-03
    • 2020-05
    • 2020-06
    • 2020-07
    • 2020-12
    • 2021-01
    • 2021-05
    • 2021-06
    • 2021-07
    • 2021-08
    • 2021-10
    • 2021-11
    • 2021-12
    • 2022-01
    • 2022-02
    • 2022-03
    • 2022-04
    • 2022-05
    • 2022-06
    • 2022-07
    • 2022-08
    • 2022-09
    • 2022-10
    • 2022-11
    • 2022-12
    • 2023-01
    • 2023-02
    • 2023-03
    • 2023-04
    • 2023-05
    • 2023-06
    • 2023-07
    • 2023-08
    • 2023-09
    • 2023-10
    • 2023-11
    • 2023-12
    • 2024-01
    • 2024-02
    • 2024-03
    • 2024-04
    • 2024-05
    • 2024-06
    • 2024-07
    • 2024-08
    • 2024-11
    • 2025-02
    • 2025-04
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客