首页 > 文章列表 > 地图读写的竞争条件

地图读写的竞争条件

403 2024-02-06
问题内容

在此跟进旧帖子。

我正在迭代 flatproduct.catalogs 切片并在 golang 中填充我的 productcatalog 并发映射。我正在使用 upsert 方法,这样我就可以仅将唯一的 productid 的 添加到我的 productcatalog 地图中。

下面的代码由多个 go 例程并行调用,这就是我在这里使用并发映射将数据填充到其中的原因。此代码在后台运行,每 30 秒填充并发映射中的数据。

var productrows []clientproduct
err = json.unmarshal(byteslice, &productrows)
if err != nil {
    return err
}
for i := range productrows {
    flatproduct, err := r.convert(spn, productrows[i])
    if err != nil {
        return err
    }
    if flatproduct.statuscode == definitions.done {
        continue
    }
    r.products.set(strconv.itoa(flatproduct.productid, 10), flatproduct)
    for _, catalogid := range flatproduct.catalogs {
        catalogvalue := strconv.formatint(int64(catalogid), 10)
        r.productcatalog.upsert(catalogvalue, flatproduct.productid, func(exists bool, valueinmap interface{}, newvalue interface{}) interface{} {
            productid := newvalue.(int64)
            if valueinmap == nil {
                return map[int64]struct{}{productid: {}}
            }
            oldids := valueinmap.(map[int64]struct{})
            
            // value is irrelevant, no need to check if key exists 
            // i think problem is here
            oldids[productid] = struct{}{}
            return oldids
        })
    }
}

下面是我的吸气剂在同一个类中,上面的代码在那里。主应用程序线程使用这些 getter 从地图获取数据或获取整个地图。

func (r *clientrepository) getproductmap() *cmap.concurrentmap {
    return r.products
}

func (r *clientrepository) getproductcatalogmap() *cmap.concurrentmap {
    return r.productcatalog
}

func (r *clientrepository) getproductdata(pid string) *definitions.flatproduct {
    pd, ok := r.products.get(pid)
    if ok {
        return pd.(*definitions.flatproduct)
    }
    return nil
}

这就是我从 productcatalog cmap 读取数据的方式,但我的系统在以下范围语句上崩溃 -

// get productcatalog map which was populated above
catalogproductmap := clientrepo.getproductcatalogmap()
productids, ok := catalogproductmap.get("211")
data, _ := productids.(map[int64]struct{})

// i get panic here after sometime
for _, pid := range data {
  ...
}

我收到错误 - fatal 错误:并发地图迭代和地图 write

我认为问题是 r.productcatalog 是一个并发映射,但 oldids[productid] 是一个法线映射,当我在上面的 for 循环中迭代时,它会导致问题。

如何解决我遇到的这个种族问题?我能想到的一种方法是将 oldids[productid] 作为并发映射,但如果我这样做,那么我的内存会增加很多,最终会 oom。下面是我尝试过的有效方法,它解决了竞争条件,但它增加了很多内存,这不是我想要的 -

r.productCatalog.Upsert(catalogValue, flatProduct.ProductId, func(exists bool, valueInMap interface{}, newValue interface{}) interface{} {
    productID := newValue.(int64)
    if valueInMap == nil {
        // return map[int64]struct{}{productID: {}}
        return cmap.New()
    }
    // oldIDs := valueInMap.(map[int64]struct{})
    oldIDs := valueInMap.(cmap.ConcurrentMap)

    // value is irrelevant, no need to check if key exists
    // oldIDs[productID] = struct{}{}
    oldIDs.Set(strconv.FormatInt(productID, 10), struct{}{})
    return oldIDs
})

我可以采取任何其他方法,既不增加内存,又解决我所看到的竞争条件?

注意 我仍在使用没有泛型的 cmap v1 版本,它处理字符串作为键。


正确答案


您可以定义一个包含映射的结构体来控制对映射的访问,而不是简单的 map[int64]struct{} 类型:

type myMap struct{
   m sync.Mutex
   data map[int64]struct{}
}

func (m *myMap) Add(productID int64) {
   m.m.Lock()
   defer m.m.Unlock()

   m.data[productID] = struct{}{}
}

func (m *myMap) List() []int64 {
   m.m.Lock()
   defer m.m.Unlock()

   var res []int64
   for id := range m.data {
       res = append(res, id)
   }

   // sort slice if you need
   return res
}

使用上面的示例实现,您必须小心地将 *mymap 指针(而不是普通的 mymap 结构)存储在 cmap.concurrentmap 结构中。