This is unrelated to moving.
Multiple threads are executing vector::push_back()
on the same vector
but
vector::push_back()
is not threadsafe. The modifications to the vector
need to be synchronized.
A std::mutex
could be used to synchronize the calls to push_back()
:
std::vector<int> values;
std::mutex values_mutex;
void values_push_back()
{
values_mutex.lock();
values.push_back(i);
values_mutex.unlock();
}
Also, the variable i
is being shared among threads without synchronization which is will result in a race condition (a possible outcome of this is duplicate int
s added to the vector
). Consider passing the int
value as an argument to the thread to avoid this:
std::vector<int> values;
std::mutex values_mutex;
void values_push_back(int i)
{
values_mutex.lock();
values.push_back(i);
values_mutex.unlock();
}
for (int i = 0; i < 10; ++i)
{
threads.push_back(std::thread(values_push_back, i));
}
for (auto& t: threads) t.join();
As commented by bamboon prefer std::lock_guard
to ensure the lock is released if push_back()
throws (which in this case could only be bad_alloc()
but if the vector
changes to hold more complex objects that have throwing constructors it becomes more important):
void values_push_back(int i)
{
std::lock_guard<std::mutex> lk(values_mutex);
values.push_back(i);
}