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 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)