开发者

python iterators and thread-safety

开发者 https://www.devze.com 2022-12-28 13:09 出处:网络
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:

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(sel开发者_C百科f):
   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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号