Thread Safety

Aahz Maruch aahz at panix.com
Sun Jan 28 00:47:50 EST 2001


In article <980660755.2138768834 at news.silcom.com>,
Clarence Gardner  <clarence at netlojix.com> wrote:
>
>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.

That's safe, yes, for as long as the GIL exists.  I personally would
prefer to use a singleton class instance or a static module variable
rather than a "global" variable, but that's more a matter of taste.

Another thing you could do to make your code a bit more efficient would
be to do this:

    if not (PendingDataStorage or PendingStatusUpdates):
        time.sleep(10)

In the end, though, I think I'd most likely split this loop into two
separate threads and use Queue.Queue() unless you have a specific reason
for wanting to batch up work every ten seconds.  That would guarantee
the best response time.
-- 
                      --- Aahz (Copyright 2001 by aahz at pobox.com)

Androgynous poly kinky vanilla queer het    <*>     http://www.rahul.net/aahz/
Hugs and backrubs -- I break Rule 6

"I heard Commentary and Dissent had merged and formed Dysentary."



More information about the Python-list mailing list