我将值附加到一个线程中的嵌套列表,然后在主线程中使用列表理解复制不断增长的嵌套列表。我的示例中需要使用线程锁吗?我知道
list.append()
方法是线程安全的,但是在使用列表理解复制数据时是否需要使用锁?
如果我确实需要使用锁,那么在
copy_data()
中使用锁而不是在 GrowList._add_to_list()
中使用锁是否有意义?
import threading
import time
class GrowList(object):
def __init__(self):
self.data = []
self.stop_event = threading.Event()
self.add_to_list()
def _add_to_list(self):
sample = [1, 2, 3, 4]
while not self.stop_event.is_set():
self.data.append(sample)
time.sleep(1.0)
def add_to_list(self):
self.t = threading.Thread(target=self._add_to_list)
self.t.start()
def stop(self):
self.stop_event.set()
self.t.join()
def copy_data(nested_list):
return [row[:] for row in nested_list]
我认为你至少需要一把锁来在一个线程中进行迭代 同时附加在另一个中,我认为它不会 当你不使用时复制数据时使用锁是有意义的 追加到列表时的锁。使用锁的要点 是在列表上声明一些所有权。
您可能会问的另一个问题是,这样做的意义何在? 不使用锁?您可以通过简单地保持代码整洁 将
self.data = []
替换为 self.data = MySafeList()
并
通过单独编写一个带锁的小型线程安全列表类。
通过使用众多的之一可以很容易地编写它
@synchronized
装饰器随处可用。例如
允许列表理解的 __iter__
方法可以是
写为
@synchronized
def __iter__(self):
return iter(list(list.__iter__(self)))