Thread safetyness in Python

Tim Peters tim at zope.com
Wed Jul 3 12:15:02 EDT 2002


[Oren Tirosh]
> So a+=1 isn't atomic, but l+=[1] is. Interesting.

[Skip Montanaro]
> How so?
>
>     >>> def f(l):
>     ...   l += [1]
>     ...
>     >>> dis.dis(f)
>               0 LOAD_FAST                0 (l)
>               3 LOAD_CONST               1 (1)
>               6 BUILD_LIST               1
>               9 INPLACE_ADD
>              10 STORE_FAST               0 (l)
>              13 LOAD_CONST               0 (None)
>              16 RETURN_VALUE
>
> Looks to me like there's the opportunity for another thread to sneak in
> there and modify l between the LOAD_FAST and STORE_FAST instructions...

The deal is that the STORE_FAST is really a nop in this case:
list.__iadd__(obj) returns obj, and rebinding obj (the STORE_FAST) to the
same value is a semantic nop.

Another way to look at it is that

    list += iterable

is equivalent to

    list.extend(iterable)

except that under the covers the implementation makes the former act like

    list.extend(iterable)
    list = list

The bytecode for the "list = list" part has no effect in the end, so doesn't
matter.






More information about the Python-list mailing list