tags:

views:

93

answers:

2

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!

+3  A: 

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.

Drakosha
+1  A: 

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.

MSalters
I completely agree with this. When you are writing multi-threaded code you should aim to make your operations atomic. Even _if_ this operation on its own is safe; if you are using mutexs or critical sections for other operations you must use them for this too. If you are worried about performance use a readers writer lock to enable multiple readers to size() but only a singe writer.
iain