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!
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.
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.
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.
There is no thread-safe guaranty on anything in the containers and algorithms of the the STL. So, No.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With