views:

98

answers:

1

I have a class which is being operated on by two functions. One function creates a list of widgets and writes it into the class:

def updateWidgets(self):
   widgets = self.generateWidgetList()
   self.widgets = widgets

the other function deals with the widgets in some way:

def workOnWidgets(self):
   for widget in self.widgets:
      self.workOnWidget(widget)

each of these functions runs in it's own thread. the question is, what happens if the updateWidgets() thread executes while the workOnWidgets() thread is running?

I am assuming that the iterator created as part of the for...in loop will keep some kind of reference to the old self.widgets object? So I will finish iterating over the old list... but I'd love to know for sure.

+3  A: 

updateWidgets() doesn't alter self.widgets in place (which would have been a problem) but rather replaces it with a new list. The references to the old one are kept at least until the for loop in workOnWidgets() has finished, so this should not be a problem.

Simplified, what you're doing is kind of like this:

>>> l=[1,2,3]
>>> for i in l:
...    l=[]
...    print(i)
...
1
2
3

However, you'd be running into problems if you modified the list you're iterating over:

>>> l=[1,2,3]
>>> for i in l:
...    l[2]=0
...    print(i)
...
1
2
0
Tim Pietzcker
great answer, and great examples. thanks!
Igor