List iterator thread safety

Carl Banks pavlovevidence at gmail.com
Thu Aug 27 10:50:16 EDT 2009


On Aug 27, 7:25 am, Hendrik van Rooyen <hend... at microcorp.co.za>
wrote:
> On Thursday 27 August 2009 15:26:04 Carl Banks wrote:
>
> > 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.
>
> Its not too bad - if you crook a bit - the trick is that you iterate over the
> list backwards when you are removing stuff based on index, so that the
> remainder does not get jumbled up by losing their positions, as happens when
> you do it going forwards.

That's only if you remove the "current item".  The OP has different
threads accessing the list at the same time, so I have to assume that
item being remove is not necessarily the current iteration.


Getting back to the game example, suppose your "list of objects in the
scene" looks like this:

[ HandsomeHero, Enemy1, Bullet1, Enemy2, Bullet2, Enemy3]

It might happen that Bullet1.update() detects a collision with Enemy2,
thus killing Enemy2, which means Enemy2 would have to be removed
before the next iteration.  Otherwise you're updating a zombie.
(Which, parenthetically, is another approach.)

Conversely, suppose Bullet2.update() detects a collision with Enemy1,
and Enemy1 is removed from the list.  Then Enemy3 is going to be
skipped.

In order to handle both cases (where an item could be removed ahead of
or before the current item), you have to keep track of the current
index and adjust it.  A list iterator won't work.


For the record, I use a more sophisticated system that explicitly
resolves cause and effect in my games.  That's probably beyond the
scope of this thread, though.


Carl Banks



More information about the Python-list mailing list