STD ::矢量自然线在迭代时安全

std::vector natural thread safe while iteration

本文关键字:迭代 安全 自然 STD      更新时间:2023-10-16

假设,我有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。


请注意,由于某物不是线程安全,因此不会抛出异常。当然,这并不意味着错误(无论是腐败,崩溃等)不会发生 - 他们最确定的。

此外,请注意,线程(它们都不会停止运行"。他们将继续不知道自己弄乱了一切。关键是他们无法知道。