Thread-safety of writing a std::vector vs plain array

The two are equally safe. Provided no element is accessed from multiple threads you're OK. Your parallel loop will access each element only once, and hence only from one thread.

There's space in the standard for the member functions of containers to be non-thread-safe. In this case you use vector<int>::operator[], so you'd want an explicit guarantee of thread-safety for that member, which seems reasonable since calling it even on a non-const vector doesn't modify the vector itself. So I doubt that there's a problem in this case, but I haven't looked for the guarantee [edit: rici found it]. Even if it's potentially unsafe, you could do int *dataptr = &data.front() before the loop and then index off dataptr instead of data.

As an aside, this code is not guaranteed safe for vector<bool>, since it's a special-case for which multiple elements co-exist inside one object. It would be safe for an array of bool, since the different elements of that are different "memory locations" (1.7 in C++11).


For c++11, which specifies rules for data races, the thread-safety of containers is described. A relevant section of the standard is § 23.2.2, paragraph 2:

Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector<bool>, are modified concurrently.

[ Note: For a vector<int> x with a size greater than one, x[1] = 5 and *x.begin() = 10 can be executed concurrently without a data race, but x[0] = 5 and *x.begin() = 10 executed concurrently may result in a data race. As an exception to the general rule, for a vector<bool> y, y[0] = true may race with y[1] = true. —end note ]

The mentioned § 17.6.5.9 essentially bans any concurrent modification by any standard library interface unless specifically allowed, so the section I quote tells you exactly what's allowed (and that includes your usage).

Since the question was raised by Steve Jessop, paragraph 1 of § 23.2.2 explicitly allows the concurrent use of [] in sequence containers:

For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].


The main thing it means is that if you have multiple threads accessing the vector, you can't depend on C++ to keep you from corrupting the data structure with multiple concurrent writes. So you need to use some kind of guard. On the other hand, if your program doesn't use multiple threads, as your examples don't seem to, you're perfectly fine.