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

前端 未结 4 2123
离开以前
离开以前 2021-02-07 03:47

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

4条回答
  •  萌比男神i
    2021-02-07 04:28

    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::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, 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).

提交回复
热议问题