Thread safetyness in Python

John Goerzen jgoerzen at complete.org
Wed Jul 3 08:52:32 EDT 2002


Hi,

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

1. a = a + 1
2. a = a + 2
3. list.append(x)
4. list.remove(x)
5. del(list[0])

Here's why I'm asking:

1. In C, a++ would be atomic because CPUs have an atomic increment
operation, in most cases.  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.

2. This operation is not possible with just the increment operator.

3. If this is not thread-safe and two threads try to do it simultaneously,
it might be the case that each thread adds a new list[5] instead of one
adding list[5] and the other list[6].

4. If this is not thread-safe, both threads might remove the same item,
rather than one thread removing it and the other raising an exception.

5. If not thread-safe, both threads might remove the same item, rather than
one thread removing the first item and the next, the second.

Thanks,
John

-- 
John Goerzen <jgoerzen at complete.org>    GPG: 0x8A1D9A1F    www.complete.org



More information about the Python-list mailing list