c++ - 是否在 vector C++ 中读取和写入 vector 线程安全操作?

标签 c++ multithreading vector thread-safety

<分区>

我有下面的代码有时会出现段错误?

vector<int> myvector;
void function1()
{
    for(int i = 0;i<10;i++)
    {
        cout<<"writer thread:"<<i<<endl;
        myvector.push_back(i);
    }
}
void function2()
{
    for(int i = 0;i<10;i++)
    {
        cout<<"reader thread:";
        cout<<myvector[i]<<endl;
    }
}
int main()
{

    thread t1(function1);
    thread t2(function2);

    t1.join();
    t2.join();
}

我对一般容器和特定 vector 的线程安全规则/保证有点困惑。我在面试中被问到这个问题,并没有说出为什么写在线程上和写在其他线程不是线程安全的操作。

在下面的 vector push_back 链接中,我在“数据竞争”部分看到“否则,不会访问任何现有元素,并且同时访问或修改它们是安全的”。这个陈述如何证明 vector 写操作不是线程安全的?

http://www.cplusplus.com/reference/vector/vector/push_back/

最佳答案

来自 Scott Meyers,Effective STL,第 12 条:“对 STL 容器的线程安全抱有现实的期望”。

  • Multiple readers are safe. Multiple threads may simultaneously read the contents of a single container, and this will work correctly. Naturally, there must not be any writers acting on the container during the reads.

  • Multiple writers to different containers are safe. Multiple threads may simultaneously write to different containers.

That's all, and let me make clear that this is what you can hope for, not what you can expect.

我想我不必在这里提供任何额外的解释:)

关于c++ - 是否在 vector C++ 中读取和写入 vector 线程安全操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55185230/

相关文章:

c++:我在我的数组中得到了一个奇怪的值

c++ - MFC 对话框在失去焦点时卡住

c - 想要避免一次调用八个线程的 sempost

C++ 从电子邮件 vector 中删除

c++ - UML 图上数组的表示数组

c++ - 无效指针?

c# - NET CF 上的线程安全调用

Java嵌套同步

c++ - 由第二个数组中的值限定的随机数数组

arrays - 在 MATLAB 中将数组转换为字符串?