is +=1 thread safe

Duncan Booth duncan.booth at invalid.invalid
Thu May 1 11:14:00 EDT 2008


AlFire <spamgrinder.trylater at ggmail.com> wrote:

> But I still can not believe that +=1 is not a thread safe operation.
> 
> 
> Any clue?

The statement:

    	x+=1

is equivalent to:

      x = x.__iadd__(1)

i.e. a function call followed by an assignment.

If the object is mutable then this *may* be safe so long as you never do 
any other assignment to x (the __iadd__ method will return the object being 
mutated so the assignment would in this restricted case be a noop).

Integers are immutable, so the assignment must always rebind x to a new 
object. There is no way given Python's semantics that this could be thread 
safe.

Generating hundreds of threads is, BTW, a very good way to get poor 
performance on any system. Don't do that. Create a few threads and put the 
actions for those threads into a Queue. If you want the threads to execute 
in parallel investigate using sub-processes.

The threading module already has a function to return the number of Thread 
objects currently alive.



More information about the Python-list mailing list