我正在阅读有关各种 STL 容器的线程安全的信息 link 现在我遇到了仅适用于 C++11 的这一点
Different elements in the same container can be modified concurrently by different threads, except for the elements of
std::vector<bool>
(for example, a vector ofstd::future
objects can be receiving values from multiple threads)
这是否意味着如果我有一个被多个人使用的方法
同时线程(notice the method does not have any locks)
void ChangeValue(int index , int value)
{
someVector[index] = value;
}
以上方法安全吗。我的理解是它只对 C++11 是安全的。 但是,当我查看链接中提到的其他声明时
All const member functions can be called concurrently by different threads on the same container. In addition, the member functions begin(), end(), rbegin(), rend(), front(), back(), data(), find(), lower_bound(), upper_bound(), equal_range(), at(), and, except in associative containers, operator[], behave as const for the purposes of thread safety (that is, they can also be called concurrently by different threads on the same container). More generally, the C++ standard library functions do not modify objects unless those objects are accessible, directly or indirectly, via the function's non-const arguments, including the this pointer.
我得出的结论是,在 C++03 中也可以安全地使用上述方法。 如果我的理解正确,请告诉我。
最佳答案
在 C++03 标准下询问是否线程安全是没有意义的——C++03 及更早版本没有任何线程或线程安全的概念。
ChangeValue
是无数据竞争的(由 C++11 及更高版本定义)只要没有两个线程为 index
传递相同的参数,否则调用传递相同的参数通过函数外部的某种方式相互同步。
关于C++11/C++03 和 std::vector 线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31149513/