Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 STL containers and thread safety

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 they don't, due to performance reasons. But then again, that's why we have both std::vector::operator[] and std::vector::at.

like image 847
Šimon Tóth Avatar asked Oct 17 '12 10:10

Šimon Tóth


People also ask

Are STL containers thread-safe?

The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe.

Are C functions thread-safe?

The stdio library is thread-safe if the _mutex_ * functions are implemented. Each individual stream is protected by a lock, so two threads can each open their own stdio stream and use it, without interfering with one another.

What are the three classes of containers?

The three types of containers found in the STL are sequential, associative and unordered.

How many containers are there in STL?

In C++, there are generally 3 kinds of STL containers: Sequential Containers. Associative Containers. Unordered Associative Containers.


2 Answers

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<bool>, 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<std::future<int>> 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.)

like image 113
Jonathan Wakely Avatar answered Sep 23 '22 18:09

Jonathan Wakely


I think STL containers offer the following basic thread-safety guarantee:

  • simultaneous reads of the same object are OK

  • simultaneous read/writes of different objects are OK

But you have to use some form of custom synchronization (e.g. critical section) if you want to do something different, like e.g. simultaneous writes on the same object.

like image 32
Mr.C64 Avatar answered Sep 26 '22 18:09

Mr.C64