简体   繁体   English

如果另一个线程在向量的末尾推送一个元素,向量上的迭代器将无效吗?

[英]Iterator on a vector invalidated if another thread pushes an element on the end the vector?

I was wondering if I need a mutex lock in this case. 我想知道在这种情况下是否需要互斥锁。

I have a vector my_vector that is operated on by two threads. 我有一个由两个线程操作的向量my_vector

Thread 1: 线程1:

my_vector.push_back(element)
// send a request for the element, the subject of which thread 2 will receive
// continues

Thread 2: 线程2:

// receive element
iter = my_vector.find(element) // This **will** be found in the vector
// do stuff using iter

My question is: it is possible that thread 1 could add more elements to my_vector whilst thread 2 is using iter ... but should this matter? 我的问题是:线程2使用iter ,线程1可能会向my_vector添加更多元素……但这应该重要吗? If items are only added to the end of the vector, surely the iterator looking at the element in the middle won't be affected? 如果仅将项目添加到向量的末尾,那么确定中间元素的迭代器是否不会受到影响?

Thanks for any thoughts on this. 感谢您对此的任何想法。

You are required to use a lock if an object may be accessed in one thread while it's modified in another. 如果可能在一个线程中访问一个对象而在另一个线程中对其进行了修改,则必须使用锁。

but should this matter? 但这有关系吗? If items are only added to the end of the vector, surely the iterator looking at the element in the middle won't be affected? 如果仅将项目添加到向量的末尾,那么确定中间元素的迭代器是否不会受到影响?

Don't reason like this. 不要这样推理。 It will cause nothing but pain. 它只会造成痛苦。 Stick to things that are guaranteed to work rather than doing things that you think should work because you can't think of any way they could go wrong. 坚持要保证能行得通的事情,而不要做您认为应该行得通的事情,因为您无法想到它们可能会出错。 An obvious case -- what if the push_back resizes the vector? 一个明显的情况-如果push_back调整向量的大小会怎样?

It is likely to be affected eventually. 最终可能会受到影响。

Vectors work by moving memory around. 向量通过移动内存来工作。 Whenever you add an element to a vector whose memory is full, the existing elements are first copied to newly allocated, larger memory and then the element is added. 只要将元素添加到内存已满的向量中,就会先将现有元素复制到新分配的更大的内存中,然后再添加该元素。 Then the original memory is destroyed. 然后,原始内存被破坏。 So any iterators pointing to the original memory are invalidated. 因此,指向原始内存的所有迭代器都是无效的。

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

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