doubipiao1611 2017-12-18 08:04
浏览 36
已采纳

Go同步地图面临的并发问题

I am having problems with Go's sync.Map. Below are the details:

I created a global sync map like:

var MySyncGlobalMap = sync.Map{}

and on an event I populate this map with the intended structure as map[int64]map[string]interface{}. So basically I want to populate the sync map with key as int64 and value as another sync map of structure map[string]interface{}. Below is how I populate the map:

//below is the innerSync map. recSet is returned from DB call in the format : []map[string]interface{}
var innerSyncMap = sync.Map{}
for _, record := range recSet {

    sKey := record["key"].(string)
    value := record["value"]
    innerSyncMap.Store(sKey, value)
}
MySyncGlobalMap.Store(jobID, innerSyncMap)

Now there will be multiple threads which will be accessing this map and do some operations. There will be constant updates to the inner sync map. Once the processing is done on the key of the inner sync map, that key will be deleted from that map.

I will know that a job is complete once the inner sync map becomes empty.

Now since there are multiple threads accessing this map I receiving a panic:

Fatal error: concurrent read and write

I am still wondering that even after using sync map I am facing this issue.

Can any one point out what am I doing wrong?

  • 写回答

1条回答 默认 最新

  • dongxie1907 2017-12-20 06:20
    关注

    I figured out what the problem with the code was. I used the sync.Map as Value type instead of pointers.

    So, I was making copies of the underlying mutexes. And on read/write operations the lock was on the copy instead of original mutex.

    Changing the map to use pointers solved the problem.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题