Python threading and sharing variables

Thomas Nyberg tomuxiong at gmx.com
Wed Jul 5 04:26:09 EDT 2017


On 07/05/2017 10:05 AM, pozz wrote:
> 
> 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?

I think the general rule would be that no it's not safe to skip the
locks. It's true that with cpython, your method shouldn't run into
problems, but that's just a quirk of how you're using it. I look at from
another perspective, if it's true that no locks actually are necessary,
then why are you using the shared variables in the first place. In this
case, the information needs to be send from the worker thread to the
main thread, but you don't need for any other threads to see it. This
only really requires a single "channel" (e.g. a queue) and not for the
variable to further exposed.

Also personally I just find it much clearer. I was very confused what
your code was doing and basically need to step through it to understand.

Cheers,
Thomas



More information about the Python-list mailing list