Python threading and sharing variables

pozz pozzugno at gmail.com
Wed Jul 5 03:56:53 EDT 2017


I'd like to launch *and control* a long thread. I want to print the 
progress of the long thread in the main thread. It's a GUI script, here 
it's a console script only to simplify.

import threading
import time

class MyClass:
     def start(self):
         self.max = 5
         self.pause = 1
         t = threading.Thread(target=self.thread)
         t.start()
         i = -1
         while self.cnt != self.max - 1:
             if i != self.cnt:
                 print("{:d}".format(self.cnt))
                 i = self.cnt
         print("Finished")

     def thread(self):
         for i in range(self.max):
             self.cnt = i
             time.sleep(self.pause)

c = MyClass()
c.start()


It seems it works, but I'm not sure it is the correct way to share the 
variable self.cnt. It is only written in the long thread and only read 
in the main thread.
Could a single Python instruction be interrupted (in this case, self.cnt 
= i)? Should I use a locking mechanism when reading/writing?

What about if the variable is more complex, for example a list or 
dictionary? Even in this case, is it safe to avoid locking on a shared 
variable if the operation on the variable is performed in a single 
Python instruction?



More information about the Python-list mailing list