简体   繁体   中英

Multiple threads operating on std::vector: do I need a lock in this case?

I have a 'listener' thread that looks at a std::vector 'receivers', puts it into an array of size receivers.size() , and executes an MPI_Waitany on it, which will return the index in the array of the element that completed a receive operation.

The element that is completed is then erased from the receivers vector via:

receivers.erase(receivers.begin() + completed_index);

However, other threads can push elements to the 'receivers' vector whilst this is going on, via:

receivers.push_back(receiver_message);

Is this dangerous? I know that iterators can become invalid if an added-element causes C++ to resize the vector, but as the iterator in my erase happens at a single point and is then thrown away, is that not an atomic operation for my purposes?

If locks are required, do I then need to lock the vector every time I want to access any element of it? Eg

MPI_Start(&(receivers.at(0)->request));

Needs a lock even though element 0 never changes? ('request' is just a member of the element)

Thanks

The simple rule is that if any of the threads is going to write to the vector (which translates loosely as "modifies it in any way"), then you need to use locks for all threads to achieve a coherent view.

You can get by without locks if and only if the vector is strictly read-only.

Internally a vector in the STL is implemented as an contiguous block of memory of that vector type. When you modify a vector it is possible that it resizes the memory block and copies existing values into a new place before removing old memory. Multiple concurrent accessors might mutate this internal memory in the old location and therefore must lock. On top of this, vector keeps internal counts of current allocated size and current usage which is not synchronized in anyway. You can destroy internal book keeping without synchronization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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