Python iterators and thread safety

I have a class on which two functions work. One function creates a list of widgets and writes them to a class:

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

another function deals with widgets in some way:

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

each of these functions is launched in its own thread. the question is what happens if the updateWidgets() thread workOnWidgets() while the workOnWidgets() thread is running?

I assume that an iterator created as part of the for...in loop will keep some reference to the old self.widgets object? Therefore, I will finish repeating the old list ... but I would love to know for sure.

+4
source share
1 answer

updateWidgets() does not change self.widgets in place (which would be a problem), but replaces it with a new list. Links to the old are kept, at least until the for loop in workOnWidgets() completes, so this should not be a problem.

Simplified, what you do is something like this:

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

However, you will have problems if you change the list you are repeating:

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

Source: https://habr.com/ru/post/1308459/


All Articles