osdir.com


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

Python threading and sharing variables


Il 05/07/2017 09:56, pozz ha scritto:
 > [...]
> 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?


Ok, maybe this atomic behaviour depends on the Python implementation, so 
it's better to avoid relying on atomicity and use a lock to access 
shared variables from different running thread.

However in my simple case one thread writes the variable and the other 
reads it. In this case is it safe to avoid locks?