C++11/C++03 和 std::vector 线程安全

标签 c++ multithreading c++11 vector stl

我正在阅读有关各种 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 of std::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/

相关文章:

c++ - 唯一指针 : pointer being freed was not allocated when emplaced in list

c++ - 在函数内调用 "continue"

Python 线程模块无法识别 args

java - ScheduledThreadPoolExecutor.schedule 留下的空闲线程

c++ - 将返回指针的 C API 函数包装到宏调用中

c++ - 这种语法合法吗?

c++ - windbg 找到我的应用程序 pdb 文件,即使我没有透露它的路径

c++ - 通过套接字发送带有 vector 的 C++ 对象

c++ - 为什么在将 boost::units::make_scaled_unit 与 liter_base_unit 一起使用时会出现编译错误?

c# - 终止由Visual Studio插件生成的所有线程的正确方法是什么?