0
class WorkerThread(threading.Thread):
    someList = []

    __init__(self, someVariable):
       self.someVariable = someVariable

    __start__(self, queue):
        while True:
            id = queue.get()
            self.doWork(id)
            queue.task_done()

     doWork(self, id):
         result = do_some_slow_operation(id)
         lock = Thread.Lock()
         with lock:
             self.someList.append(result)

I have a very basic scope question. In the above example, via trial and error, it seems all threads have scope to someList. But self.someVariable's scope is limited to each thread. Can someone confirm this is correct, or if someList should have an explicit additional keyword or annotation identifier to indicate it is a synchronized class variable?

Tim
  • 1,174
  • 12
  • 19

1 Answers1

0

self.someVariable is created within the scope of each thread, while someList is created within the class. All WorkerThread objects should have access to the same someList, but each will have a different instance of self.someVariable.

But there is a bit of a catch, reading and writing to a class variable like this is not really thread safe. You should use a lock when working with class variables. See this thread for a bit more info. I also recommend reading up on thread synchronization if you are going to be working with multi-threading.

Community
  • 1
  • 1
Jacob H
  • 864
  • 1
  • 10
  • 25
  • Ok, that's what I was observing, and I appreciate the confirmation. Thanks. I did use a lock with the write as well; since I could not verify list.append was thread safe. – Tim Feb 15 '16 at 05:00