简体   繁体   English

在MacOSX上,使用g ++,std :: vector .size()线程安全吗?

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

I have a std::vector<...> that is shared in two threads. 我有一个std :: vector <...>在两个线程中共享。

Both of them make calls to vec->size(); 他们两个都调用vec-> size();。

Can this be a source of race conditions? 这可以成为比赛条件的来源吗? I'm hoping not since vec->size() is const. 我不希望因为vec-> size()是const。

Thanks! 谢谢!

If you are calling ONLY vec->size() you are safe. 如果调用vec->size() ,则很安全。 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. 一旦您调用任何更改方法(例如push_back ,竞赛都可能导致获得错误的大小。

Probably not. 可能不会。 The problem isn't really in vec->size(), it's in all the other functions as well. 问题实际上不在vec-> size()中,在所有其他函数中也是如此。

Consider this: vector::size() is typically calculated directly from members, eg .end - .begin . 考虑一下:vector :: size()通常直接从成员(例如.end - .begin )计算得出。 Now what happens with a push_back on one thread? 现在在一个线程上使用push_back会发生什么? 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. 结果,当他们调用size() ,将使用旧值进行计算。

An obvious exception is when the vector doesn't change size after the creation of the threads. 一个明显的例外是当创建线程后向量不改变大小时。 The threads will never have outdated information. 线程将永远不会过时的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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