I have a method defined inside a class as follows:
from Queue import Queue
from threading import Thread, Lock
class Example(object):
def f(self):
things = [] # list of some objects to process
my_set = set()
my_dict = {}
my_list = []
def update(q, t_lock, my_set, my_dict, my_list):
while True:
thing = q.get()
new_set, new_dict, new_list = otherclass.method(thing)
with t_lock:
my_set = set_overlay(my_set, new_set)
my_dict.update(new_dict)
my_list += new_list
q.task_done()
q = Queue()
num_threads = 10
thread_lock = Lock()
for i in range(num_threads):
worker = Thread(target=update, args=(q, thread_lock, my_set, my_dict, my_list))
worker.setDaemon(True)
worker.start()
for t in things:
q.put(t)
q.join()
As you can see I'm trying to update the variables my_set
, my_dict
, and my_list
with some results from the threaded update
method defined inside the f
method. I can pass them all to the update function, but this only works for mutable datatypes.
I updated this to use threading.Lock()
as user maxywb
suggested, but I would like to keep the same questions below open to be answered now that the lock is included.
My questions are:
- Is this threadsafe? Can I guarantee that no updates to any of variables will be lost?
- What if I wanted to throw an immutable variable into the mix like an
int
, that was added to from the results ofotherclass.method(thing)
? How would I go about doing that? - Is there a better way to do this/architect this? The idea here is to update variables local to a class method from a thread, while sharing a (hopefully) threadsafe reference to that variable across threads.