Is python memory shared between theads?

Klaas mike.klaas at gmail.com
Fri Dec 1 17:09:51 EST 2006


John Henry wrote:
> Wesley Henwood wrote:

> > Is this normal behavior?  Based on the little documentation I have been
> > able to find on this topic, it is normal behavior.  The only way to use
> > same-named variables in scripts is to have them run in a different
> > process, rather than different threads.
>
> Yes and No.
>
> local variables are local to each threads.   Global variables are
> global to the threads.

That is somewhat misleading.  _All_ variables accessible from two
threads are shared.  This includes globals, but also object attributes
and even local variables (you could create a closure to share a local
among threads).

The only reason locals appear "thread-local" is that locals are
"invokation-local" in that they are different bindings every time a
function is executed, and generally a single invokation of a function
is confined to a single thread.

Another way to share local variables is to create a generator, and call
.next() in two different threads... the local variables are
simulatneously modifiable by both threads.

FWIW, there is also threading.local().

-MIke




More information about the Python-list mailing list