Thread Safety

Tim Peters tim.one at home.com
Sun Jan 28 01:07:48 EST 2001


[Clarence Gardner]
> I have a multithreaded program in which I use the following pattern in
> various places, because I was pretty sure it was thread-safe.  But since
> I was just reading the thread about statcache, I thought I'd ask
> just to be sure.  The code is in a function that runs periodically
> and disposes of accumulated work:
>
> def Periodic():
>     global PendingDataStorage,PendingStatusUpdates
>     while 1:
>         time.sleep(10)
>         Data,PendingDataStorage = PendingDataStorage,[]
>         if Data:
>             StoreDataPoints(Data)
>         Data,PendingStatusUpdates = PendingStatusUpdates,[]
>         if Data:
>             SetErrorStatus(Data)
>
> The code I'm talking about are the two binding statements, where
> I bind to two names which form a tuple, rather than two statements,
> which would certainly not be thread-safe.

It's impossible to say:  "thread safety" is not an absolute judgment, it's
relative to the invariants your particular algorithm needs to preserve.  As
an extreme example,

x = 0
def periodic():
    global x
    while 1:
        time.sleep(.1)
        x += 1

may very well be thread-safe if the only thing the *rest* of your code cares
about is that it never sees an x < 0.

In your particular case, why try to be clever at all?  The loop doesn't wake
up more than once per 10 seconds, so the cost of a mutex lock/unlock pair
would be insignificant.  In return, you get certainty.

cleverness-is-the-#1-cause-of-thread-bugs-ly y'rs  - tim


PS:

>>> import dis
>>> def f():
...     x, y = 0, 1
...
>>> dis.dis(f)
          0 SET_LINENO               1

          3 SET_LINENO               2
          6 LOAD_CONST               1 (0)
          9 LOAD_CONST               2 (1)
         12 BUILD_TUPLE              2
         15 UNPACK_SEQUENCE          2
         18 STORE_FAST               0 (x)
         21 STORE_FAST               1 (y)
         24 LOAD_CONST               0 (None)
         27 RETURN_VALUE
>>>

Python executes bytecodes atomically, but makes no guarantees beyond that.
Do you still think you're "threadsafe"?





More information about the Python-list mailing list