何时在迭代中使用互斥锁。 c++
C++ 提供了非常方便的方法来通过迭代来遍历容器,
for(vector<int>::const_iterator p = c.begin(); p!=c.end();p++){}
但是如果在进行此操作时,有人c.push_back(10)
。
它会打破循环吗?
每次使用容器操作时都应该使用互斥锁吗?
谢谢。
C++ provides very convinient way to traverse the container with iteration,
for(vector<int>::const_iterator p = c.begin(); p!=c.end();p++){}
but if when this is undergoing, someone c.push_back(10)
.
Will it break the loop?
Should I use mutex every time I use container operation?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,这里有一个竞争条件。
如果您要从多个线程使用 STL 容器,并且这些线程中至少有一个可能会修改该容器,则需要同步对该容器的访问。
最简单的方法是使用互斥锁。
另一种选择是找到或实现一个提供您所需功能的线程安全容器。
Yes, there is a race condition here.
If you are going to be using an STL container from multiple threads and at least one of those threads may modify the container, you need to synchronize access to the container.
The easiest way to go about doing this is to use a mutex.
Another option would be to find or implement a thread-safe container that provides the capabilities you need.
是的,当可以从另一个线程进行写入时,您应该这样做。
http://www.sgi.com/tech/stl/thread_safety.html
Yes, you should, when writes are possible from another threads.
http://www.sgi.com/tech/stl/thread_safety.html
你有两个问题。首先,您遇到迭代器失效问题。由于
push_back
增加了向量的大小,因此它有可能调用分配。每当向量的容量(不是元素数量)发生变化时,向量中的所有迭代器都会失效。这是最容易处理的方法,方法是确保在开始循环之前调用reserve()
,以确保向量中有足够的空间来满足所有未来的push_back
尝试,同时循环运行。另一个问题,正如其他帖子中提到的,当插入可能与正在访问的元素同时运行时,您会遇到竞争条件。
You have two issues. First, you have an iterator invalidation issue. Because
push_back
increases the size of the vector, it has the possibility of invoking an allocation. whenever the capacity (not number of elements) of a vector changes, all iterators into the vector are invalidated. This is easiest to deal with by making sure to callreserve()
before beginning the loop to make sure there is enough space in the vector to satisfy all futurepush_back
attempts while the loop runs.The other issue, as mentioned in the other posts, you have a race condition when an insert may be running concurrently to the element being accessed.
是的,您需要使用互斥锁来保护整个向量。这是不使用向量在线程之间共享数据的一个很好的理由。大多数时候我们使用队列,用锁保护push/pop。
如果您需要使用大缓冲区共享数据,我建议使用某种带有“页面”的自定义结构,因此,您可以只阻塞一小部分,并让其他线程同时在内存的不同位置运行。
yes, you need to protect the whole vector with a mutex. And that is a good reason to dont use vectors to share data between threads. Most of the time we use queues, protecting push/pop with locks.
If you need to share data using big buffers, I would recommend using some kind of custom structure with "pages", so, you can block only a small part, and letting other threads run on different places of the memory at the same time.
最简单的方法是在迭代前加锁,完成
The easiest way is to lock before iteration and unlock after finishing