osdir.com


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

Python threading and sharing variables


On Wed, Jul 5, 2017 at 12:14 PM, Peter Otten <__peter__ at web.de> wrote:
> Chris Angelico wrote:
>
>> You can be confident that a single assignment will happen atomically.
>> Even if "self.cnt = i" requires multiple instructions to perform
>
> For name binding
>
> cnt = i
>
> maybe, but
>
> self.cnt = i
>
> can execute arbitrary Python code (think __setattr__()). With threads I'd
> rather play it safe.

Computed properties that require setting multiple values are a problem
that may require locking.

Assignment of a single variable in an unoptimized namespace isn't
completely immune to this -- in principle. Think __setitem__,
__getitem__, __hash__, and __eq__. For example:

    >>> exec('cnt = 42; cnt = 43; cnt', NoisyNS())
    __setitem__('cnt', 42)
    __hash__('cnt')
    __setitem__('cnt', 43)
    __hash__('cnt')
    __eq__('cnt', 'cnt')
    __getitem__('cnt')
    __eq__('cnt', 'cnt')

It's reasonable to assume a namespace uses a built-in dict and str
keys (names) -- or at least types that don't do anything unusual that
introduces concurrency problems.