C++11 STL containers and thread safety

前端 未结 3 1190
野性不改
野性不改 2020-11-28 03:57

I have trouble finding any up-to-date information on this.

Do C++11 versions of STL containers have some level of thread safety guaranteed?

I do expect that

3条回答
  •  不知归路
    2020-11-28 04:47

    Since the existing answers don't cover it (only a comment does), I'll just mention 23.2.2 [container.requirements.dataraces] of the current C++ standard specification which says:

    implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector, are modified concurrently.

    i.e. it's safe to access distinct elements of the same container, so for example you can have a global std::vector> of ten elements and have ten threads which each write to a different element of the vector.

    Apart from that, the same rules apply to containers as for the rest of the standard library (see 17.6.5.9 [res.on.data.races]), as Mr.C64's answer says, and additionally [container.requirements.dataraces] lists some non-const member functions of containers that can be called safely because they only return non-const references to elements, they don't actually modify anything (in general any non-const member function must be considered a modification.)

提交回复
热议问题