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

I have std :: vector <...> which is shared by two threads.

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

Could this be a source of race conditions? I hope that since vec-> size () is a constant.

Thanks!

+4
source share
2 answers

If you call ONLY vec->size() , you are safe. But it’s somehow hard to believe. As soon as you call any change method, for example push_back , the race can lead to the wrong size.

+4
source

Probably not. The problem is not vec-> size (), it is also in all other functions.

Consider this: vector :: size () is usually computed directly from elements, for example. .end - .begin . Now what happens with push_back in one thread? This affects the size, obviously, through the members. He changes memory. But there is no memory barrier. Other threads on other cores will just see the old memory. As a result, when they call size() , it will be calculated using the old values.

The obvious exception is that after creating the threads, the vector does not change size. Threads will never have outdated information.

+1
source

Source: https://habr.com/ru/post/1303092/


All Articles