ricky116
ricky116

Reputation: 774

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.

Thread 1:

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

Thread 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? 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.

Upvotes: 0

Views: 255

Answers (2)

maditya
maditya

Reputation: 8896

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.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182829

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?

Upvotes: 3

Related Questions