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 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧