removeall() in list
Fredrik Lundh
fredrik at pythonware.com
Sat Jan 12 04:51:02 EST 2008
castironpi at gmail.com wrote:
> I'm writing an NxN observer pattern, mostly for my own personal
> exploration. Two threads -might- be calling 'Disconnect' at the same
> time, and I can't even guarantee that the function runs properly.
>
> for emelem in [ e for e in emlist if e.func is func ]:
> try:
> emlist.remove( emelem )
> except ValueError:
> pass
so use a lock. it's a whopping two lines of code:
creation:
lock = threading.Lock()
usage:
with lock:
for emelem in ...
...
more here:
http://effbot.org/zone/thread-synchronization.htm
and btw, looping over a list to figure out what you want to remove from
that list is a bit pointless. better just create a new list:
with lock:
# get rid of all func instances
emlist = [e for e in emlist if e.func is not func]
an alternative approach would be to replace emlist with a dictionary,
keyed on func objects. that'll let you remove all items associated with
a given function with a single atomic operation:
del emdict[func]
</F>
More information about the Python-list
mailing list