c ++ 11“基于范围是否为”线程安全?

时间:2015-02-21 22:27:36

标签: c++ multithreading c++11 thread-safety

我有一个环境,由两个std :: vector中的行和点建模。 我想计算这个环境生成的字段。我多进程了。由于环境在开始时是完全定义的,因此线程应该只读取它,因此我不会使用任何同步化herethere

问题出现了:当我遍历环境中的行时,我有两种不同的行为,这取决于我是否使用基于c ++ 11范围的语句或者我是否使用更常见的for语句与迭代器。 似乎基于范围的不是线程安全的,我想知道为什么?

如果我不能正确地假设,那可能意味着我有一个更深层次的问题,可能会再次出现。

这是一段代码,第一个工作人员似乎工作,第二个工作人员挑起了一个段错误。

Worker::worker(Environement const* e, int id):threadId(id),env(e)
{
}

// worker that seems to do his job.
void Worker::run() const
{
    cout<<"in thread n "<<_threadId<<endl;
    vector<Line> const* lines = &env->_lines;

    for(std::vector<Line>::const_iterator it = lines->begin() ;it != lines->end(); ++it ){
        it->hello();
    }
}

// create a segfault
void Worker::run2() const
{
    cout<<"in thread n "<<_threadId<<endl;
    vector<Line> const& lines = env->_lines;

    for(auto it : lines){
        it.hello();
    }
}

如果需要,简化数据结构:

struct Line
{
    void hello() const {std::cout<<"hello"<<std::endl;}
}

struct Environment
{
    std::vector<Line> _lines;
    std::vector<Point> _points;
}

0 个答案:

没有答案