is +=1 thread safe

Gary Herron gherron at islandtraining.com
Sat May 3 19:44:15 EDT 2008


Alexander Schmolck wrote:
> AlFire <spamgrinder.trylater at ggmail.com> writes:
>
>   
>>> The threading module already has a function to return the number of Thread
>>> objects currently alive.
>>>       
>> I have threads within threads - so it does not suit me :-(.
>>     
>
> How about using a scalar numpy array? They are mutable, so I assume that x +=
> 1 should be atomic.
>   

No NO NO!   The only way to increment a variable in memory is through a
three step process:

  Load a register from a memory location
  Increment the register
  Store the value back into memory.

Ages ago, there were architectures that would do an increment on a
memory location in an atomic way, but with the current (RISC)
architectures these are three separate operations.

A good compiler may be able to eliminate some of these operations by
keeping the variable in question in a register,  but this just worsens
the problem with respect to threads since each thread has it's own set
of register values.

Gary Herron

> 'as
> --
> http://mail.python.org/mailman/listinfo/python-list
>   





More information about the Python-list mailing list