Do I Need To Use Threading Locks In This Example?
I append values to a nested list in one thread, and I copy the growing nested list with list comprehension in the main thread. Do I need to use threading locks in my example? I kno
Solution 1:
I think you need a lock at least for iterating in one thread while appending in the other, and I think it wouldn't make sense to use a lock when copying the data when you don't use a lock when appending to the list. The point of using a lock is to claim some ownership on the list.
Another question that you may ask is what is the point of
not using a lock ? You could keep your code clean by simply
replacing self.data = []
by self.data = MySafeList()
and
by writing separately a small thread safe list class with a lock.
It could be written very easily by using one of the numerous
@synchronized
decorators available here and there. For example
the __iter__
method that allows list comprehension could be
written as
@synchronized
def __iter__(self):
return iter(list(list.__iter__(self)))
Post a Comment for "Do I Need To Use Threading Locks In This Example?"