Thread safetyness in Python

Tim Peters tim at zope.com
Wed Jul 3 11:22:33 EDT 2002


[John Goerzen]
> I have some questions about what is thread-safe in Python.  Can
> someone tell me whether each of the following are thread-safe:

Yes <wink>.  Assuming you mean thread-safe in the sense of sequential
consistency:

> 1. a = a + 1
> 2. a = a + 2

No and no.  Others have suggested Python

    a += 1

is atomic, but it isn't.

> 3. list.append(x)
> 4. list.remove(x)
> 5. del(list[0])

Yes, yes, and yes.  Note that del isn't a function, and

    del list[0]

is more idiomatic.  Also,

    x = list.pop(0)

is an atomic way to remove the first item and retrieve its value in one
gulp.

> Here's why I'm asking:
>
> 1. In C, a++ would be atomic because CPUs have an atomic increment
> operation, in most cases.

Do a reality check before relying on this.  I don't know of any platform
where C compiles a++ to atomic code, even assuming a is of integral type.
On platforms that have some sort of atomic increment instruction, you
typically need to use inline assembly, or call a vendor-supplied builtin
function, to get at it.  Else you're going to get code like this (from a
listing of generated code on an Intel box, where 'a' is of the native int
type):

; 6    :     a++;

  00022	8b 55 fc	 mov	 edx, DWORD PTR _a$[ebp]
  00025	83 c2 01	 add	 edx, 1
  00028	89 55 fc	 mov	 DWORD PTR _a$[ebp], edx

> In Python, it might be the case that if two threads hit this code at the
> same time, a would only be incremented once because both threads would
> read a, add 1, and store the same result back.  So one might need a lock
> here.

Yes, although the same is equally true of C a++.






More information about the Python-list mailing list