theads & global namespaces
Andrew Cooke
Andrew.Cooke at p98.f112.n480.z2.fidonet.org
Thu Jul 1 08:54:04 EDT 1999
From: Andrew Cooke <andrew at andrewcooke.free-online.co.uk>
In article <377A5C88.32A1FAB6 at notes.cba.ufl.edu>,
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.
Hi,
I may be teaching my granny to suck eggs here, so ignore this if it's
obvious, but in general you should not spin a thread while waiting for
another thread to do something (this doesn't fix your global problem,
it's just advice about multi-threaded programming).
All my multi-threaded experience is with java, but the classes in
Python are similar, so I'll have a go at explaining how it "should" be
done and someone can point out my errors...
(Incidentally, whether or not your program works as it is - assuming
the global access thing is fixed - will depend on the platform you
runit out, and the threads implementation used. Using conditions,
it will run on any platform).
from threading import *
globalX = 0
def test():
c = Condition()
c.acquire() # get hold of the condition
t = Thread(target=XChanger, argcs=c)
t.start()
c.wait() # this halts this thread and releases c
print globalX
c.release()
class XChanger:
def run(cond): # cond is c, passed in from the args in Thread
cond.acquire() # waits for c to be released (in c.wait() above)
globalX = globalX + 1
cond.notifyAll() # signal the other thread to restart when...
cond.release() # ...we release this
print globalX # should print 0
test() # should print 1 inside test()
print globalX # should print 1
(This is only one way of doing things - it may not even be best, but
it shows what I'm thinking of). Doug Lea has written a very good
book about threads, but it discusses Java. Because the Python threading
module is similar, you may find it useful (especially if you already
know Java).
There's also a completely different approach to using threads, which
is based on a (fairly ancient) book by Hoare called Communicating
Sequential Processes. It is more elegant, but not as popular (it's
used in occam, and there is a Java library to support it, but nothing
for Python that I know of - ask me if you're interested and I can ask
on a mailing list I am subscribed to).
Cheers,
Andrew
Sent via Deja.com http://www.deja.com/
Share what you know. Learn what you don't.
More information about the Python-list
mailing list