is +=1 thread safe

Diez B. Roggisch deets at nospam.web.de
Thu May 1 11:18:47 EDT 2008


AlFire schrieb:
> 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.

don't confuse augmented assignment with incrementation as it is offered 
by C (if your data-type actually fits into a single addressable memory 
spot, that is)

python's += works like this


a += b  <=> a = a.__iadd__(b)

Thus you actually get a situation where the expression on the right is 
evaluated but not yet assigned - and then another thread can take over 
control, computing  with the old value of a.

Diez



More information about the Python-list mailing list