osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python threading and sharing variables


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?