Does python overwrite list before loop?

Let's say that I have a list land thread t1 that repeats over lforever:

while True:
    for i in l:
        #do something

and another thread t2 randomly modifies or deletes members in l.

What happens after removal? Does t1 determine this in the current loop?

UPDATE :

  • Freeze i mean t1 get a copy l. t2 can change lfor sure

  • quoting documentation or a simple but convincing piece of code is welcome.

+5
source share
3 answers

. - "" . , .

( : http://ideone.com/0iMao):

l = list(range(10))
for i in l:
    print i
    try:
        del l[i]
    except (RuntimeError,IndexError), e:
        print e

print l

:

0
2
4
5
7
list assignment index out of range
9
list assignment index out of range
[1, 2, 4, 5, 7, 9]

, , , : http://docs.python.org/reference/compound_stmts.html#the-for-statement.

. , iter(l) , .

+7

:

>>> from threading import Thread
>>> from time import sleep
>>> liszt = ['first item', 'second item', 'third item', 'fourth item',
...         'plentee more items', "but I'm lazy"]
>>> def thread_one():
...     for i in liszt:
...             print 'Thread one found "%s"' % i
...             sleep(1)
... 
>>> def thread_two():
...     sleep(0.5)
...     print 'Thread two deleting first item.'
...     del liszt[0]
...     sleep(1)
...     print 'Thread two deleting fourth item.'
...     del liszt[3]
... 
>>> Thread(target=thread_one).start(); Thread(target=thread_two).start()
Thread one found "first item"
Thread two deleting first item.
Thread one found "third item"
Thread two deleting fourth item.
Thread one found "fourth item"
Thread one found "but I'm lazy"

, ; , , , .

, ; , .

State:             [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator position:  ^

.

State:             [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator position:     ^

.

State:             [2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator position:     ^

.

State:             [2, 3, 4, 5, 6, 7, 8, 9, 10]
Iterator position:        ^

.

State:             [2, 3, 4, 5, 7, 8, 9, 10]
Iterator position:        ^

Et cetera. , , . , , - .

, iter. for x in y iter(y). , iter(liszt) listiterator, , next() , , . , for Python.

+2

The list is accessible from both threads, not for freezing. the iterator will “know” that the participants were deleted and skipped if you do not have explicit access to the index beyond the length of the list. deletions themselves are thread safe.

if you need a real list lock, protect it with a mutex or copy it.

0
source

All Articles