设计问题:std :: map的线程安全 [英] Design Problem: Thread safety of std::map

查看:1161
本文介绍了设计问题:std :: map的线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用std :: map来实现我的本地哈希表,这将被多个线程同时访问。
我做了一些研究,发现std :: map不是线程安全的。
因此我将在地图上使用互斥体进行插入和删除操作。
我计划有单独的互斥,每个映射条目一个,以便它们可以独立地修改。

I am using std::map to implement my local hash table, which will be accessed by multiple threads at the same time. I did some research and found that std::map is not thread safe. So I will use a mutex for insert and delete operations on the map. I plan to have separate mutex(es), one for each map entry so that they can be modified independently.

我需要把查找操作在临界区?
操作会被插入/删除操作影响吗?
有比任何更好的实现比使用std :: map可以照顾一切吗?

Do I need to put find operation also under critical section? Will find operation be affected by insert/delete operations? Is there any better implementation than using std::map that can take care of everything?

推荐答案

deed需要放在一个关键部分,但你可能想要有两个不同的锁,一个用于写入和一个用于读取。写锁定是独占的,但是如果没有线程保持写锁定,几个线程可以同时读取没有问题。

You will in deed need to put find in a critical section, but you might want to have two different locks, one for writing and one for reading. The write lock is exclusive but if no thread holds the write lock several threads may read concurrently with no problems.

这样的实现将适用于大多数STL实现,符合标准。 std :: map 通常使用红黑树,当读取元素时不会改变。如果地图是使用斜面树实现的,则树将在查找期间更改,并且只有一个线程可以一次读取。

Such an implementation would work with most STL implementations but it would not be standards compliant, however. std::map is usually implemented using a red-black tree which doesn't change when elements are read. If the map was implemented using a splay tree instead, the tree would change during lookup and only one thread could read at a time.

对于大多数情况,我建议使用两把锁。

For most purposes I would recommend using two locks.

这篇关于设计问题:std :: map的线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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