更新时间:2023-11-13 23:21:04
我认为您至少需要一个锁才能在一个线程中进行迭代 同时添加另一个,而我认为不会 不使用时复制数据时使用锁的感觉 追加到列表时的锁.使用锁的要点 是要在列表中声明某些所有权.
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.
您可能要问的另一个问题是:
不使用锁?您可以简单地保持代码清洁
用self.data = MySafeList()
替换self.data = []
并
通过分别编写一个带锁的小线程安全列表类.
使用众多方法之一可以很容易地编写它
@synchronized
装饰器在这里和那里都可用.例如
允许列表理解的__iter__
方法可以是
写为
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)))