Threads modify "global" variable -- asking for trouble?

Alex Martelli aleaxit at yahoo.com
Fri Mar 17 05:34:48 CET 2006


J Rice <rice.jeffrey at gmail.com> wrote:

> My apologizes, I missed the newish FAQ entry on this.  The addrbl()
> method looks like this:
> 
>  def addRBL(self, testname, result, info=""):
>         self.testresultsRBL[testname] = result, info
> 
> So according to the FAQ, D[x] = y, where D is a dictionary, is atomic
> and therefore thread-safe.  Right?

In the current implementation specifically, for CPython exclusively, if
the hashing of testname is itself somehow 'atomic', and so is the access
to attribute testresultsRBL of object self, I do believe you might luck
out and end up "atomic" (by accident of implementation, only) if
everything's just right. Of course, any tiny change (any different
implementation of Python, any type that's not a pure primitive, any
future version of Python, etc, etc) could break this extremely fragile
set of circumstances -- Python as a language makes no guarantees of
atomicity for anything except the synchronization primitives (of which
Queue is the most powerful). There was a rather heated exchange on the
subject quite recently on this group.

Just put a lock acquire/release around this assignment (and any _use_ of
the same dictionary) and you should be vastly safer, IMNSHO.


Alex



More information about the Python-list mailing list