run a function in another processor in python

MRAB python at mrabarnett.plus.com
Fri Dec 10 14:18:41 EST 2010


On 10/12/2010 17:52, Dennis Lee Bieber wrote:
> On Fri, 10 Dec 2010 23:02:24 +1100, Astan Chee<astan.chee at gmail.com>
> declaimed the following in gmane.comp.python.general:
>
>>>>         for thread in threads:
>>>>             if not thread.is_alive():
>>>>                 threads.remove(thread)
>>>>
>
> 	I can see a potential flaw just in that... You are changing the
> length of the list you are iterating over, which is never recommended.
>
> 	Consider this simplistic attempt at removing the even numbers from a
> list:
>
>>>> tlist = [1, 1, 0, 0, 2, 2, 3, 4, 3, 4, 5, 6, 7, 8]
>>>> for t in tlist:
> ... 	if t % 2 == 0:
> ... 		tlist.remove(t)
> ...
>>>> tlist
> [1, 1, 0, 2, 3, 3, 5, 7]
>>>>
>
> 	Doesn't work if a pair of even numbers are adjacent. In your case,
> adjacent "dead" threads will not be removed.
>
>   Something like the following may be safer:
>
> 		dead = []
> 		for t in threads:
> 			if not t.is_alive():
> 				dead.append(t)
> 		for dt in dead:
> 			threads.remove(dt)

I think this will be more efficient:

     threads = [t for t in threads if t.is_alive()]



More information about the Python-list mailing list