vector
, like all STL containers, is not thread-safe. You have to explicitly manage the synchronization yourself. A std::mutex
or boost::mutex
could be use to synchronize access to the vector
.
Do not use a flag as this is not thread-safe:
- Thread A checks value of
isInUse
flag and it is false
- Thread A is suspended
- Thread B checks value of
isInUse
flag and it is false
- Thread B sets
isInUse
to true
- Thread B is suspended
- Thread A is resumed
- Thread A still thinks
isInUse
is false
and sets it true
- Thread A and Thread B now both have access to the
vector
Note that each thread will have to lock the vector
for the entire time it needs to use it. This includes modifying the vector
and using the vector
's iterators as iterators can become invalidated if the element they refer to is erase()
or the vector
undergoes an internal reallocation. For example do not:
mtx.lock();
std::vector<std::string>::iterator i = the_vector.begin();
mtx.unlock();
// 'i' can become invalid if the `vector` is modified.