is +=1 thread safe
Gary Herron
gherron at islandtraining.com
Sun May 4 12:03:32 EDT 2008
Alexander Schmolck wrote:
> Gary Herron <gherron at islandtraining.com> writes:
>
>
>> But... It's not!
>>
>> A simple test shows that. I've attached a tiny test program that shows this
>> extremely clearly. Please run it and watch it fail.
>>
>
> In [7]: run ~/tmp/t.py
> final count: 2000000
> should be: 2000000
>
> (I took the liberty to correct your test to actually do what I said, namely
> use a numpy.array; just replace ``count = 0`` with ``import numpy; count =
> numpy.array(0)``).
>
The test was meant to simulate the OP's problem, but even with your
suggestion of using numpy, it *still* fails! Just start increasing the
number of increments by a factor of 2, 4, 10 until it fails:
final count: 1999998
should be: 2000000
final count: 5999997
should be: 6000000
final count: 5995068
should be: 6000000
(Surprisingly, using numpy makes this test *much* slower, meaning the
increment executes many more instructions, which implies hitting a
thread context switch at exactly the critical point is much less
common. But it can happen if you run the test long enough.)
I am running this on a Core2 Duo CPU, but the GIL should prevent that
from affecting the result of the run.
I've reattached the file with the numpy change (and a larger loop
counter) for others to try.
Gary Herron
>
> 'as
>
> p.s. please don't send me copies to on-list replies, at least not without
> explicitly mentioning the fact -- I've got better things to do then guessing
> whether something was meant to be off-list or not.
>
My apologies.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: t.py
Type: application/python
Size: 525 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20080504/65db1ba0/attachment-0001.bin>
More information about the Python-list
mailing list