basic python threading question

Donn Cave donn at u.washington.edu
Fri Sep 29 16:54:11 EDT 2000


Quoth "Tom" <nospam at nospam.com>:
| "Aahz Maruch" <aahz at panix.com> wrote in message
| news:8r2hdl$6rr$1 at panix6.panix.com...
|> In article <q_IA5.42927$dZ2.15588642 at news3.rdc1.on.home.com>,
|> Tom <nospam at nospam.com> wrote:
|>|
|>| This would be a problem for threading, unless all atomic objects are
|>| thead-safe.  Now, all atomic objects appear to me to be immutable.  Are
|>| immutable objects inherently thread-safe in Python (even if the ref count
|>| change)?
|>
|> Yes, immutable objects are thread-safe.  Remember that assignment in
|> Python is a binding operation, not a modification operation.

| But, even an immutable object has its reference count modified by a binding
| operation.  And this sounds like a problem to me, since (quoting from
| section 8.1 of  API Ref):
|
| "when two threads simultaneously increment the reference count of the same
| object, the reference count could end up being incremented only once instead
| of twice. "

In the present implementation, though, if that could actually happen it
would be through a bug at the C level, not in Python.  The interpreter
has a global lock that prevents operations like assign/bind from happening
in two concurrent threads.  Correctly implemented modules can allow
concurrent execution, but only where all but one thread are in external
functions.

This is the kind of thing you need to know.

As another poster has already mentioned, thread safety isn't really about
different kinds of objects.  Mutable vs. immutable isn't that useful of
a distinction.  How about a file descriptor open on a UNIX pipe?  it's
just an integer, and of course you can use it for arithmetic all you want,
but don't let two threads write to it at once.

| I'm finding threading on Python to be more complicated than threading in C.
| It also seems that threading in any interpreted environment must have a
| fairly heavy overhead, and so is best avoided.

Threading is best avoided, period.  I mean, if you can do approximately
the same thing without threads, then you would have to be insane to use
threads.  But I'm posting this from a multithreaded program, written in
python, at the moment I count 15 threads.  There's no overhead on this
132Mhz computer, and Python doesn't make it more difficult nor does it
make it easier.  The use of threads adds a dimension to the complexity
of the program, that's all.  The overhead is in your head.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list