默认情况下,std :: vector线程安全且并发吗?为什么或者为什么不? [英] Is std::vector thread-safe and concurrent by default? Why or why not?

查看:233
本文介绍了默认情况下,std :: vector线程安全且并发吗?为什么或者为什么不?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使动态数组具有线程安全性和并发性意味着什么?
例如, std :: vector

What does it mean to make a dynamic array thread-safe and concurrent? Say, for example, std::vector.


  1. 两个线程可能想要插入相同的位置。不需要同步,因为将按照线程调度完成同步。

  2. 一个线程正在擦除而另一个线程将访问同一元素?我相信这不是数据结构问题,而是使用问题。

那么在 std :: vector 使其默认为线程安全并发,还是默认为线程安全并发?

So is there anything that needs to be done over std::vector to make it thread-safe and concurrent or is it thread-safe and concurrent by default?

推荐答案

C ++ 11安全地对标准库中的容器线程进行了以下说明:

C++11 says the following about the thread safetly of containers in the standard library:


23.2.2容器数据竞赛[container.requirements.dataraces]

23.2.2 Container data races [container.requirements.dataraces]

为了避免数据竞赛(17.6.5.9),实现中
应考虑以下功能设为const:开始结束
rbegin rend 数据查找 lower_bound
upper_bound equal_range at ,以及关联或$ b $除外b无序关联容器, operator []

For purposes of avoiding data races (17.6.5.9), implementations shall consider the following functions to be const: begin, end, rbegin, rend, front, back, data, find, lower_bound, upper_bound, equal_range, at and, except in associative or unordered associative containers, operator[].

尽管(17.6.5.9),当包含对象的内容在相同序列中的不同元素
中时,除 vector< bool> 被同时修改

Notwithstanding (17.6.5.9), implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector<bool>, are modified concurrently.

基本上从多个线程中读取容器是好的,修改容器中已经存在的元素也可以(只要它们是不同的元素)。

So, basically reading from a container from multiple threads is fine, and modifying elements that are already in the container is fine (as long as they are different elements).

因此,您的另外两个特定问题中的 std :: vector

So, neither of your two more specific questions are thread safe for std::vector:

1是线程安全的)1)将两个线程插入到向量正在修改向量本身-而不是存在的单独元素。

1) Two threads inserting into the vector is modifying the vector itself - not existing separate elements.

2)一个线程擦除和其他步行操作来访问同一元素并不安全,因为从向量中擦除一个元素不是一个被保证是线程安全的操作(或如标准所说的那样从数据争用中解放出来)。

2) One thread erasing and other walking to access the same element is not safe because erasing an element from the vector isn't an operation that is promised to be thread safe (or "free from data races", as the standard puts it).

要执行t安全地操作软管将要求程序本身进行一些外部同步。

To perform those operations safely will require that the program impose some external synchronization itself.

这篇关于默认情况下,std :: vector线程安全且并发吗?为什么或者为什么不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆