is +=1 thread safe

Alexander Schmolck a.schmolck at gmail.com
Sun May 4 20:37:38 EDT 2008


Gary Herron <gherron at islandtraining.com> writes:

> The test was meant to simulate the OP's problem, but even with your suggestion
> of using numpy, it *still* fails!  

Well, although I haven't tested it extensively, it doesn't appear to fail for
me, with numpy 1.02 and an AMD Athlon(tm) XP 2800+ under linux 2.6, so it is
possible that numpy's implementation has changed wrt. to GIL usage (or that
the platform makes a difference, but that seems less likely):

In [26]: run ~/tmp/t.py
final count: 2000000
  should be: 2000000

In [27]: run ~/tmp/t.py
final count: 2000000
  should be: 2000000

In [28]: run ~/tmp/t.py
final count: 2000000
  should be: 2000000

In [29]: run ~/tmp/t.py
final count: 2000000
  should be: 2000000

In [30]: run ~/tmp/t.py
final count: 10000000
  should be: 10000000

I don't claim to have deep knowledge of threading/GIL issues under python, but
my understanding is that you can certainly write an extension that does this
atomically if required (although the bytecode for immutable and mutable is the
same, I think the problem in the immutable case is that the rebinding that
occurs after the inplaceadd step is to a new object, and hence not a no-op).
This isn't to distract from your and Aahz point downthread: this is inherently
a very brittle way to go about things. On the other hand if you have some
already dodgy legacy code (as the OP indicated) that you want to make work
with a minimum of fuzz, it might still be a reasonable option.

'as



More information about the Python-list mailing list