Say I have a list l and a thread t1 iterating over l for ever:
while True:
for i in l:
#do something
and another thread t2 randomly modify or delete members in l.
What happens after a deletion? Does t1 detect that in the current loop?
UPDATE:
-
By freeze I mean t1 get a copy of
l. t2 can modifylfor
sure -
citing documentation or simple but persuading code snippet are
welcomed.
No. The list is not frozen – your iterator will not “break” in the sense of raising an exception. Instead, it will keep moving forward through the list, with results that are possibly surprising.
Consider this code (Snippet at ideone here: http://ideone.com/0iMao):
It produces this output:
Which is probably not what you wanted or expected, although it is apparently well-defined: http://docs.python.org/reference/compound_stmts.html#the-for-statement .
Instead, you can either lock the list, or take a copy. Note that
iter(l)does not take a copy internally, and will have the same effect as just iterating over the list directly.