C++11 std::vector in concurrent environment

不想你离开。 提交于 2019-12-05 02:28:50
hmjd

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 ints 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);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!