简体   繁体   中英

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

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!

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, eg .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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM