theads & global namespaces
Michael P. Reilly
arcege at shore.net
Wed Jun 30 21:04:23 CEST 1999
Taylor Anderson <andersdt at notes.cba.ufl.edu> wrote:
: Greetings all,
: I am trying to share globals between threads. Is is possible for me to
: share globals between threads that call functions from different
: modules? Thus far I have had little success. I ask this question
: because I would prefer not to put all my code in one module.
: For example, I have 2 .py files: a.py and b.py. b.py contains the
: function ('foo()') to be executed under the new thread, as well as the
: global variable 'x'. a.py contains the call to
: start_new_thread(foo,()). a.py also tries to use the global variable x.
: x = 0
: def foo():
: global x
: x = x + 1
: from b.py import *
: if __name__ == '__main__':
: start_new_thread(foo, ())
: while 1:
: if x != 0:
: print x
: So far, my code in a.py does not detect any change in x. Any
: suggestions for a workaround?
This isn't just a threads problem, but a namespace problem.
When you create a variable, it is a name bound to an object, a reference
if you will. When you assign to that same name, often another object
will be bound. When you import using "from...import *" you create
new bindings to these objects in the new module, but not referencing the
What this means is, when you use "from...import...", assignments within
the module can be hidden from the calling module:
Python 1.5.2 (#14, Jun 11 1999, 16:31:09) [C] on aix4
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> import foo
>>> from foo import x
>>> x is foo.x
>>> foo.x = "hi"
>>> x is foo.x
When foo.x was changed, x (in the local module) did not change with it,
becuase the variable "foo.x" is not the same as the variable "x". Even
if both pointed to the same object at first.
Your solution is to import "b" and reference the variable as "b.x".
[If your system is any more complex than what you describe above, you
might have other problems with "x" within a multi-threaded environment
if you do not have some type of synchronization.]
More information about the Python-list