Python threading and sharing variables

Chris Angelico rosuav at gmail.com
Wed Jul 5 04:26:28 EDT 2017


On Wed, Jul 5, 2017 at 5:56 PM, pozz <pozzugno at gmail.com> wrote:
> 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?

You can be confident that a single assignment will happen atomically.
Even if "self.cnt = i" requires multiple instructions to perform
(which it probably doesn't), there's still going to be some moment
before the change has happened at all, and then some moment when the
change has completely happened, and you won't get a context switch in
between.

This is NOT the case if you try to do an increment (eg "self.cnt +=
1"), but for what you're doing here, it should be fine.

That said, though, you may still find that a queue is better, as per
Thomas's suggestion.

ChrisA



More information about the Python-list mailing list