ar2015
ar2015

Reputation: 6150

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.

Upvotes: 3

Views: 2020

Answers (3)

T.C.
T.C.

Reputation: 137425

[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[].

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.

Upvotes: 4

BiagioF
BiagioF

Reputation: 9725

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. So each array cell is not overlapped among others.

Upvotes: 3

Zbynek Vyskovsky - kvr000
Zbynek Vyskovsky - kvr000

Reputation: 18845

Generally, std::vector is not thread safe, but the above code will work because the backing array is preallocated with assign() method.

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.

Upvotes: -1

Related Questions