在Map C ++中同时访问不同的键 [英] Concurrent access to different keys in Map C++

查看:203
本文介绍了在Map C ++中同时访问不同的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个线程,其中一个线程A向地图插入一个键X,同一个键X被该线程A频繁修改。

I have two threads where one thread "A" inserts a key X to the map and the same key X is being modified by that thread "A" frequently.

在特定点,线程A完成对该键X的修改,然后线程B将读取键X并从地图中删除键X。

At a particular point the thread "A" completes modifications to that key X and then thread "B" will read the key "X" and delete the key "X" from the map.

线程B读取和删除地图时,线程A将同时插入和写入一些其他键(不是同一个键X )。

While the thread "B" reads and deletes the map , the thread "A" will insert and write some other keys in the map(not the same key X) concurrently.

在这种情况下,地图是否需要同步?由于线程B确定键X被线程A完全修改,并且不会对该键X进行更多的并发修改。

In this case , does the map needs to be synchronized? As the thread "B" is sure that the key "X" is completely modified by thread "A" and no more concurrent modifications will be made for that key "X".

推荐答案

是,需要同步。

插入和删除更改可能与其他类似操作重叠的地图类的内部状态(即使它们用于不同的键)。

Inserting and deletion can change internal state of the map class that can overlap with other similar operations (even if they are for different keys).

当线程A更新您不需要的对象锁定地图。映射保证迭代器和对象指针在插入/删除下是稳定的,所以你的对象不会被触摸。

While thread A updates the object you don't need to lock the map. Map guarantees that iterators and object pointers are stable under insertions/deletions so your object won't be touched.

这篇关于在Map C ++中同时访问不同的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆