c++ 当其他线程尝试读取时,push_back返回到向量-竞态条件?[重复]

klr1opcd  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(89)

此问题在此处已有答案

std::vector, thread-safety, multi-threading(4个答案)
Is std::vector or boost::vector thread safe?(3个答案)
5天前关闭。
我有一个函数,它将元素添加到std::vector中,并在给定的线程中运行:

// called in one thread    
void foo(std::vector<int>& v) {
  // use v.push_back()
}

字符串
让其他线程使用基于范围的for循环尝试从v读取数据是否安全?

// called in other threads
void g(std::vector<int>& v) {
  for(const auto& elem:v) {
    // read only
  }
}


在我看来,这可能是一个竞争条件,因为当其他线程试图读取v时,它的大小可能会改变。这确实是不安全的代码吗?

bxpogfeg

bxpogfeg1#

这是一个经典的Race条件。您需要一个锁(如std::mutex)来保护vector免受并发访问。

相关问题