List iterator thread safety

Carl Banks pavlovevidence at gmail.com
Thu Aug 27 09:26:04 EDT 2009


On Aug 27, 5:03 am, "Emanuele D'Arrigo" <man... at gmail.com> wrote:
> On Aug 27, 2:01 am, a... at pythoncraft.com (Aahz) wrote:
>
> > Well, I'm not sure about exceptions, but you almost certainly won't get
> > the results you want.
>
> What I'd like in this context is to iterate through the items in the
> list without processing the same item twice and without skipping item
> that are in front of the current iterator position. Somehow I can't
> quite prove to myself if this is possible or not over multiple
> threads. I.e. a dictionary will throw an exception about the object
> changing size while iterating through it. A list doesn't, hence the
> question.

Deleting items from a list while iterating over it is a bad idea,
exceptions or not.

Hmm, this sounds like something someone might do for a game.  You have
a list of objects, and in a given time step you have to iterate
through the list and update each object.  Problem is, one of the
enemies is kill before you get to it, so you would like to remove the
object from the list while iterating.  Not an easy problem.

For this simple appeoach, I would suggest writing a custom container
(with an underlying list) with state to keep track of the current
iterating position.  Whenever an item is removed the index is modified
(so as to prevent skipping objects), and because you are keeping track
of the index yourself there is an iterator that might throw an
exception.

With threads, you would need to use a Condition or something to
sychronize access to the object.


Carl Banks



More information about the Python-list mailing list