线程安全的c ++映射 [英] Thread-safety of c++ maps
问题描述
这是关于线程安全 std :: map
。现在,同步读取是线程安全的,但写入不是。我的问题是,如果我每次都添加唯一的元素到地图,这将是线程安全吗?
This is about thread safety of std::map
. Now, simultaneous reads are thread-safe but writes are not. My question is that if I add unique element to the map everytime, will that be thread-safe?
-
例如,如果我有一个这样的地图
std:map< int,std :: string> myMap
和我总是添加新的密钥,从不修改现有的键值,这将是线程安全的吗?
So, for an example, If I have a map like this
std:map<int, std::string> myMap
and I always add new keys and never modify the existing key-value, will that be thread-safe?
更重要的是,这会给我带来任何随机的运行时行为吗?
More importantly, will that give me any random run-time behavior?
添加新密钥是否也被视为修改?如果在添加时密钥总是不同,那么它应该是线程安全的,因为它修改了内存的独立部分。
Is adding new keys also considered modification? If the keys are always different while adding, shouldn't it be thread-safe as it modifies an independent part of the memory?
谢谢
Shiv
Thanks Shiv
推荐答案
1)当然不是
2)是的,我希望你在测试过程中不会遇到它。
2) Yes, I hope you'll encounter it during testing, not later
3)是的,是的。新元素添加在不同的位置,但许多指针在此期间被修改。
3) Yes, it is. The new element is added in a different location, but many pointers are modified during that.
在大多数(如果不是全部)实现中,地图是由某种树实现的。在树中插入新元素通过重置节点来修改它,通过重置指针来指向不同的节点。因此它不是线程安全的
The map is implemented by some sort of tree in most if not all implementations. Inserting a new element in a tree modifies it by rearranging nodes by means of resetting pointers to point to different nodes. So it is not thread safe
这篇关于线程安全的c ++映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!