gpt4 book ai didi

c++ - 如果另一个线程将元素推送到 vector 的末尾, vector 上的迭代器会失效吗?

转载 作者:行者123 更新时间:2023-11-28 00:42:03 26 4
gpt4 key购买 nike

我想知道在这种情况下是否需要互斥锁。

我有一个由两个线程操作的 vector my_vector

线程 1:

my_vector.push_back(element)
// send a request for the element, the subject of which thread 2 will receive
// continues

线程 2:

// receive element
iter = my_vector.find(element) // This **will** be found in the vector
// do stuff using iter

我的问题是:线程 1 可能会向 my_vector 添加更多元素,而线程 2 正在使用 iter...但这有关系吗?如果只在vector的末尾添加items,那么看中间元素的迭代器肯定不会受到影响吧?

感谢您对此的任何想法。

最佳答案

如果一个对象可以在一个线程中访问而另一个线程中修改它,则需要使用锁。

but should this matter? If items are only added to the end of the vector, surely the iterator looking at the element in the middle won't be affected?

不要这样推理。它只会带来痛苦。坚持那些保证有效的事情,而不是做你认为应该有效的事情,因为你想不出任何可能出错的方法。一个明显的例子——如果 push_back 调整 vector 的大小怎么办?

关于c++ - 如果另一个线程将元素推送到 vector 的末尾, vector 上的迭代器会失效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18393239/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com