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.

Answers


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.


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?


Need Your Help

Huge overhead to loading StanfordOpenNLP model in Java?

java memory nlp stanford-nlp

I'm trying to use StanfordNLP to do coreference resolution on chunks of text relating to a given topic, and while trying to load in the StanfordCoreNLP model, it at first completely ran out of memory

Does SQL Azure Cache rows that have just been created?

sql-server sql-azure

I have a stored procedure that does an insert of a row like this:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.