"is stl vector concurrent read thread-safe?" Code Answer


yes for the scenario you mention, it is perfectly thread safe.

actually, stl is not a correct way of referring it.
it is the c++ standard library.

the c++03 standard does not talk about concurrency at all, so the concurrency aspect is left out as an implementation detail for compilers. so the documentation that comes with your compiler is where one should look to for answers related to concurrency.

most of the stl implementations are not thread safe as such.
but for concurrent reads of same object from multiple threads most implementations of stl are indeed thread safe.


msdn says:

a single object is thread safe for reading from multiple threads. for example, given an object a, it is safe to read a from thread 1 and from thread 2 simultaneously.

the dinkumware stl-documentation says:

multiple threads can safely read the same container object. (there are nunprotected mutable subobjects within a container object.)

gcc documentation says:

we currently use the sgi stl definition of thread safety, which states:

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. if multiple threads access a single container, and at least one thread may potentially write, then the user is responsible for ensuring mutual exclusion between the threads during the container accesses.

so from the above, yes it is thread safe in gcc to have concurrent reads of same object from multiple threads.

note: gcc's standard library is a derivative of sgi's stl code.

By esafresa on September 21 2022

Answers related to “is stl vector concurrent read thread-safe?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.