Threads

Skip Montanaro skip at pobox.com
Wed May 22 09:54:11 EDT 2002


    Mark> r.j.cunningham at virgin.net (Robert Cunningham) wrote:

    >> Hopefully someone can clarify this for me, I have n threads running
    >> and a global var c now sometimes these threads may update c (c += 1
    >> or c -= 1). My question is do I need to use a lock or something, at
    >> the moment I don't, I assumed += is 'atomic' - am I right??

    Mark> Very unlikely - certainly with C, += reads a memory location into
    Mark> a register, adds a value to the register, and then writes the
    Mark> value back to the memory location.

Yes, but generally not in a single machine instruction.

In Python, "c += 1" translates into something like

    LOAD_FAST      c
    LOAD_CONST     1
    INPLACE_ADD         
    STORE_FAST     c

Thread switches can occur between any of those instructions, so you do need
to lock c before fiddling it in a multithreaded application.  You might get
away with not locking c, especially if you've called sys.setcheckinterval()
with a fairly large value.

    Mark> Of course it's possible that someone will reply to this mentioning
    Mark> a python package that already does this...

Sure.  That would be the threading and Queue modules.

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
"Excellant Written and Communications Skills required" - seen on chi.jobs





More information about the Python-list mailing list