Thread safetyness in Python

Aahz aahz at pythoncraft.com
Wed Jul 3 12:48:08 EDT 2002


In article <slrnai5ssg.a67.jgoerzen at christoph.complete.org>,
John Goerzen  <jgoerzen at complete.org> wrote:
>
>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

Depends on what "a" is.  If it's a function/method local, it's
guaranteed thread-safe (assuming no pathological poking into code
objects).

Generally speaking, worrying about thread-safety of objects is the wrong
tack to take with Python.  What you want to do is make sure that only
one thread has access to any given object, usually by passing references
to the object around with Queue.Queue.

>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].

This is thread-safe.  Anything with only one bytecode is thread-safe.
You can use the dis module if you want to check it out.  The problem
comes when you use list.append(f())....
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Project Vote Smart: http://www.vote-smart.org/



More information about the Python-list mailing list