STD ::矢量自然线在迭代时安全
std::vector natural thread safe while iteration
假设,我有std :: vector和两个线程。
第一个线程是处理 erase 函数,第二个线程在 for-loop
中这种情况是线程安全吗?
第二个线程会继续运行或投掷例外吗?
#include <iostream>
#include <vector>
#include <thread>
int main()
{
std::vector<int> intContainer;
for ( int index = 0; index <= 100000; ++index){
intContainer.push_back(index);
}
std::thread t1([&](){
while ( 1 ){
intContainer.erase( std::find(intContainer.begin(), intContainer.end(), random(1, 100000) ) );
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
});
std::thread t2([&] (){
for ( auto& val : intContainer ){
std::cout << val << std::endl;
}
});
t1.join();
t2.join();
return 0;
}
它是螺纹 - 不安全,但也未定义。
它是螺纹的安全性,因为您在迭代时正在更改元素(以及向量本身)。
由于上述点(种族),这是不确定的行为)。因此,即使这是一个单线程程序(例如使用纤维),您仍然会有UB。
请注意,由于某物不是线程安全,因此不会抛出异常。当然,这并不意味着错误(无论是腐败,崩溃等)不会发生 - 他们最确定的。
此外,请注意,线程(它们都不会停止运行"。他们将继续不知道自己弄乱了一切。关键是他们无法知道。
相关文章:
- 使用自己的迭代器分配容器是否安全?
- 如果迭代器没有因插入而无效,则使用std::find和C::insert()是线程安全的
- 来自并发哈希映射的迭代器是否安全
- STD ::矢量自然线在迭代时安全
- 如果迭代器的迭代器永远不会无效,则是STD :: MAP访问线程安全
- std::map 线程安全和迭代器失效
- 在插入时同时迭代一个映射,这在什么方面是不安全的
- 螺纹安全与迭代器有效性
- 在C 中将指针固定为迭代器是否安全
- 在迭代地图时向/从地图添加/删除元素是否安全
- 有没有一种安全的方法可以迭代 std::unique_ptr<int[]>?
- 采用迭代器的类型安全模板函数
- const_cast(迭代器>秒)安全吗?
- std::transform 中的输入迭代器和输出迭代器来自同一个容器是否安全?
- C++ STL 向量迭代器与索引访问和线程安全
- 如何编写一个可以以类型安全的方式迭代泛型类型的函数
- C++迭代程序异常安全
- 按顺序比较C++迭代器安全吗
- c++ 11:在迭代时从std::unordered_map中删除单个元素是否安全?
- 使用concurrent_vector迭代器的算术:假设从迭代器中减去'begin ()'会给出索引是否安全?