简体   繁体   English

如果线程在不相交的索引范围内读写,则std :: vector线程安全吗?

[英]Is a std::vector threadsafe if the threads read and write in disjoint index ranges?

Suppose, I have a std::vector<int> of length 4, which is constant. 假设我有一个长度为4的std::vector<int> ,它是恒定的。 Then there are 4 threads, where thread i reads and writes only index i . 然后有4个线程,其中线程i只能读写索引i Is this threadsafe? 这是线程安全的吗? Can the single elements be changed independently of each other? 单个元素可以相互独立更改吗? I wonder because they are close so that they are probably loaded all at once into a cacheline. 我想知道,因为它们很近,因此可能一次将它们全部加载到缓存行中。

Does it make a difference if the index range per thread is larger than 1? 如果每个线程的索引范围大于1,是否会有所不同?

EDIT: 编辑:

I am using Visual Studio 2010 and hence C++03. 我正在使用Visual Studio 2010,因此使用的是C ++ 03。 Any hints about differences from C++03 to C++11 are welcome! 任何有关从C ++ 03到C ++ 11的差异的提示都欢迎!

Yes that's fine. 是的,没关系。 Different threads can operate on different ranges of elements. 不同的线程可以在不同范围的元素上运行。

According to the C++11 Standard: 根据C++11标准:

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

2 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. 2尽管有(17.6.5.9),当同时修改了相同对象(除了vector <bool>)中不同元素中包含的对象的内容时,仍需要实现以避免数据争用。

Edit: Before C++11 concurrency and data races are never mentioned, so the spec took no account of them and made no guarantees. 编辑:从来没有提到C++11并发性和数据争用,因此规范没有考虑它们,也没有做出任何保证。

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

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