c++ - C++ 标准库如何保证避免数据竞争?

标签 c++ thread-safety std

阅读C++11 FAQ -- Threads有一段我不明白:

Consequently, C++11 provides some rules/guarantees for the programmer to avoid data races:

  • A C++ standard library function shall not directly or indirectly access objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's arguments, including this.
  • A C++ standard library function shall not directly or indirectly modify objects accessible by threads other than the current thread unless the objects are accessed directly or indirectly via the function's nonconst arguments, including this.
  • C++ standard library implementations are required to avoid data races when different elements in the same sequence are modified concurrently.

我知道什么是数据竞争,以及一般的多线程,但我不明白这些句子在说什么。

您能解释得更清楚吗?也许有一个例子?我(即应用程序程序员)在多线程上下文中做什么是安全的还是不安全的?

如果我没有读过这些,我会猜测让多个线程调用任何类型的对象的非常量方法是不安全的,但我想这还说明了一些事情?

最佳答案

好吧,我想我是从评论中弄清楚的(如果我错了,请纠正我)。

  • 前两个是相似的——即函数只会读取或写入可通过函数参数访问的内存。

    也许这意味着,函数不会在其实现中读取或改变全局或静态数据。

    C 库中有一些函数违反了这一规则,例如 ctime .

    ctime returns a pointer to static data and is not thread-safe.

  • 第三个是说一个线程可以改变容器中的元素,而另一个线程访问不同的元素。

    这并不意味着改变容器本质上也是安全的,例如插入一个新元素。

    vector<bool> 是此规则的一个异常(exception):

    std::vector<bool> behaves similarly to std::vector, but in order to be space efficient, it ... does not guarantee that different elements in the same container can be modified concurrently by different threads.

关于c++ - C++ 标准库如何保证避免数据竞争?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70542173/

相关文章:

Python:具有短生命周期键的线程安全字典,这是正确的吗?

java - 最少阻塞 java 缓存

c++ - 如何从目录加载所有文件?

c++ - void Print(vector<string>) 函数不打印

c# - WCF 服务的线程问题

c++ - std::hash ofr 的返回值 (x86/x64)

c++ - static const的C++容器初始化列表导致栈溢出

c++ - gcc如何静态分配运行时已知长度的数组

c++ - 用随机数初始化的对象

c++ - std::map 访问速度太慢?