简体   繁体   English

分配给std :: vector元素是否是线程安全的?

[英]Is assignment to a std::vector element thread-safe?

I have made a thread pool which writes to the same vector at the same time. 我做了一个线程池,它同时写入相同的向量。

Is this implementation thread safe? 这个实现线程安全吗?

If it is not, how should I fix it? 如果不是,我应该如何解决?

std::vector<double> global_var;

void func1(int i)
{
    global_var[i]=some_computation(i /* only depends on i */);
}

void load_distribution()
{
    const int N_max=100;
    global_var.assign(N_max,0.0);
    std::vector<std::thread> th_pool;
    for(long i=0;i<N_max;i++)
        th_pool.push_back(std::thread(func1,i));

    for(std::thread& tp : th_pool)
        tp.join();
}

Update 更新资料

global_var will not be touched by any other part of the program before all threads terminated. 在终止所有线程之前,程序的任何其他部分都不会触摸global_var

Assuming your global vector is not modified by any other part of code, then your code is thread safe. 假设您的全局向量未被代码的任何其他部分修改,那么您的代码是线程安全的。

Each thread is going to write (access) into a different cell of the vector, so there is no "dirty update" problem. 每个线程都将写入(访问)向量的另一个单元中,因此没有“脏更新”问题。

Moreover the vector's type is a double, in a modern architecture is bigger than a WORD-size. 此外,向量的类型是double,在现代体系结构中大于WORD大小。 So each array cell is not overlapped among others. 因此,每个阵列单元都不相互重叠。

[container.requirements.dataraces]/1-2 : [container.requirements.dataraces] / 1-2

1 For purposes of avoiding data races ([res.on.data.races]), implementations shall consider the following functions to be const : begin , end , rbegin , rend , front , back , data , [...], at and, except in associative or unordered associative containers, operator[] . 1为了避免数据争用的目的([res.on.data.races]),实施方式应考虑以下功能为constbeginendrbeginrendfrontbackdata ,[...], at并且,除非在关联或无序关联容器中,否则是operator[]

2 Notwithstanding ([res.on.data.races]), implementations are required to avoid data races when the contents of the contained object in different elements in the same container, excepting vector<bool> , are modified concurrently. 2尽管[[res.on.data.races]),当同时修改容器中除vector<bool>之外的不同元素中包含的对象的内容时,仍需要实现以避免数据争用。

Generally, std::vector is not thread safe, but the above code will work because the backing array is preallocated with assign() method. 通常, std::vector并不是线程安全的,但是上面的代码将起作用,因为支持数组是使用assign()方法预先assign()

As long as the writers don't cause reallocating the backing array, the code will work. 只要编写者不引起重新分配后备数组,代码就可以工作。 The assign() method will preallocate enough space so it will not happen when the thread write to it. assign()方法将预分配足够的空间,因此在线程对其进行写入时不会发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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