是否在矢量C ++中读取和写入矢量线程安全操作? [英] Are read from and writing to vector thread-safe operations in vector C++?

查看:60
本文介绍了是否在矢量C ++中读取和写入矢量线程安全操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码有时会导致分段错误?

I have a below code that gives segmentation fault sometime?

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();
}

我对容器(尤其是向量)的线程安全规则/保证不感到困惑.在一次采访中有人问我这个问题,但没有说出为什么在线程上写和在其他线程上写不是线程安全操作.

I am little confused with the thread safe rules/guarantees on containers in general and vectors in particular. I was asked this question in an interview and failed to put in words why it write in on thread and write in other thread is not thread-safe operation.

,我在数据争用"部分下看到否则,将不访问任何现有元素,并且可以安全地同时访问或修改它们".该语句如何证明矢量写操作不是线程安全的?

in the below link for push_back of vectors I see "Otherwise, no existing element is accessed, and concurrently accessing or modifying them is safe" under Data Race section. How does this statement justify that vector write operation is not thread-safe?

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

推荐答案

来自Scott Meyers,有效的STL,项目12:对STL容器的线程安全性抱有现实的期望".

From Scott Meyers, Effective STL, Item 12: "Have realistic expectations about the thread safety of STL containers".

  • 多个阅读器很安全.多个线程可以同时读取单个容器的内容,这将正常工作.自然,在读取过程中一定不能有任何写程序对容器起作用.

  • 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.

我认为我不必在这里提供任何其他解释:)

I think I don't have to provide any additional interpretation here :)

这篇关于是否在矢量C ++中读取和写入矢量线程安全操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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