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 know that the list.append()
method is thread-safe, but would I need to use a lock when copying the data with list comprehension?
If I do need to use locks, would it make any sense to use a lock in copy_data()
but not in 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]