此问题在此处已有答案:
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
时,它的大小可能会改变。这确实是不安全的代码吗?
1条答案
按热度按时间bxpogfeg1#
这是一个经典的Race条件。您需要一个锁(如
std::mutex
)来保护vector
免受并发访问。