简体   繁体   English

std :: map可以在迭代过程中移动吗?

[英]Can an std::map be moved while iterating through it?

When I'm iterating through an std::map , is there a possibility that by for example adding an element to the map in another thread, the objects in it will be removed causing the iteration to be corrupt? 当我遍历std::map ,是否有可能例如通过将元素添加到另一个线程中的map来删除其中的对象,从而导致迭代被破坏? (As the iterator will be pointing to a non-existing variable as it's moved) (因为迭代器在移动时将指向一个不存在的变量)

In theory when you add an element to an std::map , all the iterators in that map should stay valid. 理论上,当您将元素添加到std::map ,该std::map中的所有迭代器都应保持有效。 But the problem is that the operations are not atomic. 但是问题在于操作不是原子的。 If the OS suspends the inserting thread in the middle of the operation and gives control back to the iterating thread, the state of std::map might be invalid. 如果操作系统在操作过程中暂停插入线程并将控制权交还给迭代线程,则std::map的状态可能无效。

You need to synchronize access to the map via mutex or something similar. 您需要通过互斥或类似方式同步对地图的访问。 Alternatively you could use concurrency friendly collection from TBB or another similar library. 另外,您可以使用来自TBB或其他类似库的并发友好集合。 TBB provides concurrent_unordered_map and concurrent_hash_map . TBB提供了concurrent_unordered_mapconcurrent_hash_map

STL containers aren't thread safe. STL容器不是线程安全的。 No guarantees at all. 完全没有保证。 So you need to synchronize access to any standard container if they are used by different threads. 因此,如果它们被不同的线程使用,则需要同步对任何标准容器的访问。

Yes--if another thread may be modifying the vector, you'll need to use something like a mutex to assure that only one thread has access to the vector at any given time. 是的-如果另一个线程可能正在修改向量,则需要使用互斥体之类的东西来确保在任何给定时间只有一个线程可以访问该向量。

With a map, the effects of a modification are much more limited -- rather than potentially moving the entire contents of a vector, a modification only affects an individual node in the map. 使用贴图时,修改的效果受到更大的限制-修改可能会影响贴图中的单个节点,而不是潜在地移动矢量的全部内容。 Nonetheless, if one thread deletes a node just as another thread is trying to read that node, bad things will happen, so you still need a mutex to assure that only one thread is operating on the map at any given time. 但是,如果一个线程在另一个线程试图读取该节点的同时删除该节点,则会发生不好的事情,因此您仍然需要一个互斥体来确保在给定的时间只有一个线程在该映射上进行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM