如何以线程安全的方式迭代容器?
问题描述
我有一个容器 (C++),我需要从不同的线程以两种方式对其进行操作:1) 添加和删除元素,以及 2) 迭代其成员.显然,在迭代发生时删除元素 = 灾难.代码如下所示:
I have a container (C++) on which I need to operate in two ways, from different threads: 1) Add and remove elements, and 2) iterate through its members. Clearly, remove element while iteration is happening = disaster. The code looks something like this:
再次,B::SomeFunction()
和 C::IterateOverStuff()
被异步调用.我可以使用什么数据结构来确保在迭代期间,my_stuff
受到保护",不受添加或删除操作的影响?
Again, B::SomeFunction()
and C::IterateOverStuff()
are getting called asynchronously. What's a data structure I can use to ensure that during the iteration, my_stuff
is 'protected' from add or remove operations?
推荐答案
听起来像一个 reader/writer需要锁.基本上,这个想法是您可能有 1 个或多个读者或单个作者.永远不能同时拥有读写锁.
sounds like a reader/writer lock is needed. Basically, the idea is that you may have 1 or more readers OR a single writer. Never can you have a read and write lock at the same time.
我认为适合您的设计的使用示例涉及进行小改动.将迭代"函数添加到拥有列表的类并使其模板化,以便您可以传递函数/仿函数来定义对每个节点执行的操作.像这样的东西(快速而肮脏的伪代码,但你明白了......):
An example of usage which I think fits your design involves making a small change. Add an "iterate" function to the class which owns the list and make it templated so you can pass a function/functor to define what to do for each node. Something like this (quick and dirty pseudo code, but you get the point...):
另一个选项是让读写器锁公开访问,并让调用者负责正确使用锁.但这更容易出错.
Another Option would be to make the reader/writer lock publicly accessible and have the caller responsible for correctly using the lock. But that's more error prone.
这篇关于如何以线程安全的方式迭代容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!