Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On MacOSX, using g++, is std::vector .size() thread safe?

Tags:

c++

macos

I have a std::vector<...> that is shared in two threads.

Both of them make calls to vec->size();

Can this be a source of race conditions? I'm hoping not since vec->size() is const.

Thanks!

like image 540
anon Avatar asked Mar 04 '10 08:03

anon


People also ask

Is std::vector size thread safe?

const and Thread Safety The C++11 standard does not expect to be able to safely call non const functions simultaneously. Therefore all classes available from the standard, e.g. std::vector<>, can safely be accessed from multiple threads in the same manner.

Is Size () thread safe?

The short answer is: "yes". To determine the need for mutual exclusion, one needs to look at the "Data races" specifications of the functions involved.

Is reading from std::vector thread safe?

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.

Is std::vector empty thread safe?

There is no thread-safe guaranty on anything in the containers and algorithms of the the STL. So, No.


2 Answers

If you are calling ONLY vec->size() you are safe. But this is somehow difficult to believe. As soon you call any changing method, such as push_back a race can cause to get the wrong size.

like image 166
Drakosha Avatar answered Oct 11 '22 11:10

Drakosha


Probably not. The problem isn't really in vec->size(), it's in all the other functions as well.

Consider this: vector::size() is typically calculated directly from members, e.g. .end - .begin. Now what happens with a push_back on one thread? It affects the size, obviously, via the members. It changes memory. But there is no memory barrier. Other threads on other cores will simply see the old memory. As a result, when they call size(), it will be calculated using the old values.

An obvious exception is when the vector doesn't change size after the creation of the threads. The threads will never have outdated information.

like image 44
MSalters Avatar answered Oct 11 '22 12:10

MSalters