I\'ve read on Stackoverflow that none of the STL containers are thread-safe for writing. But what does that mean in practice? Does it mean I should store writab
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
, 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
, 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).