thread-safe swap

Kragen Sitaker kragen at pobox.com
Wed Mar 27 15:27:01 EST 2002


Someone recommended using the idiom

    spam, eggs = eggs, spam

to get a thread-safe swap.  Does this really work?
>>> import dis
>>> def x(a, b): a, b = b, a
...
>>> dis.dis(x)
          0 SET_LINENO               1

          3 SET_LINENO               1
          6 LOAD_FAST                1 (b)
          9 LOAD_FAST                0 (a)
         12 BUILD_TUPLE              2
         15 UNPACK_SEQUENCE          2
         18 STORE_FAST               0 (a)
         21 STORE_FAST               1 (b)
         24 LOAD_CONST               0 (None)
         27 RETURN_VALUE        

So if this thread loses control anywhere between the first LOAD_FAST
and the last STORE_FAST, a value could get stored by another thread
into "b" which would then be lost.  There isn't anything keeping this
from happening, is there?




More information about the Python-list mailing list