is +=1 thread safe
Gary Herron
gherron at islandtraining.com
Thu May 1 18:33:09 EDT 2008
AlFire wrote:
> Hi,
>
> I have a piece of software which uses threads in very massive way -
> like hundreds of them generated every second.
>
> there is also a piece of code which maintains the number of
> outstanding threads, simply
>
> counter+=1 is executed when before starting the thread and counter-=1
> after it finishes.
>
> all is very simple and by the end of the program life I expect the
> counter to zero out.
>
> however I am getting values -1, -2, 1 ,2 ,3 and quite often 0 as
> expected.
>
> I guarded those statement with Lock.{acquire,release} and now it
> always returns 0.
>
>
> But I still can not believe that +=1 is not a thread safe operation.
>
>
> Any clue?
>
Of course it's not thread safe. For the same reason and more basic,
even the expression i++ is not thread safe in C++.
Any such calculation, on modern processors, requires three operations:
retrieve value of i into a register,
increment the register
write the value into i.
If a thread is interrupted anywhere within that sequence, and another
thread access i, you have a conflict. (And indeed, hardware interrupts
can occur between any two instructions.)
Gary Herron
More information about the Python-list
mailing list