is +=1 thread safe

Duncan Booth duncan.booth at invalid.invalid
Fri May 2 03:33:52 EDT 2008


Marc 'BlackJack' Rintsch <bj_666 at gmx.net> wrote:

> On Thu, 01 May 2008 15:33:09 -0700, Gary Herron wrote:
> 
>> 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.
> 
> There are no modern processors with an opcode for incrementing a memory
> location!?  At least my C64 can do that.  ;-)
> 
The operation i++ in C/C++ implies two things: it increments the memory 
location and returns the new result. That means there are at least two ways 
to generate code for this:

   increment memory
   load new value

or

   load value
   incremenent
   store

Neither of these is going to be thread-safe (even on a C64) unless you 
protect the operations somehow. The latter is probably preferred as it only 
implies two operations to memory whereas the former implies three.

Even on your C64 incrementing a memory location involves both a read and a 
write, so if you have a multi-core C64(!) there is still scope for another 
processor to get into the middle of that increment instruction.




More information about the Python-list mailing list