Thread safetyness in Python
Oren Tirosh
oren-py-l at hishome.net
Wed Jul 3 09:58:51 EDT 2002
On Wed, Jul 03, 2002 at 12:52:32PM +0000, John Goerzen wrote:
> 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])
>From www.python.org/doc/current/api/threads.html :
Therefore, the rule exists that only the thread that has acquired the
global interpreter lock may operate on Python objects or call Python/C API
functions. In order to support multi-threaded Python programs, the
interpreter regularly releases and reacquires the lock -- by default, every
ten bytecode instructions (this can be changed with sys.setcheckinterval()).
The lock is also released and reacquired around potentially blocking I/O
operations like reading or writing a file, so that other threads can run
while the thread that requests the I/O is waiting for the I/O operation to
complete.
The resolution is one bytecode operation so a+=1 is atomic but not a=a+1.
The list operations above are atomic.
Oren
More information about the Python-list
mailing list