From: Ype K. <yk...@xs...> - 2001-06-26 12:06:24
|
My reply to Adrian: >Date: Tue, 26 Jun 2001 13:58:19 +0100 >To: "Adrian St. John" <as...@pa...> >From: Ype Kingma <yk...@xs...> >Subject: Re: [Jython-users] Multiple instances of embedded Jython Interpreter >Cc: >Bcc: >X-Attachments: > >Adrian, > >you wrote: >>Hi, >> >>Does anyone know how difficult it is to get multiple embedded Jython >>interpreters running in the same Java process in separate threads? > >It's easy, you can do it from jython and from java, your choice. > >>I'm writing a multi-user game engine using Jython as the interactive >>programming environment. Each interpreter instance has its stdout/stderr >>redirected to a network connection. >> >>The problems I seem to have are: >> >>stdout/stderr for all instances get redirected to the last one set. > >Stdout/stderr are 'one per process'. You'll have to use your own >output functions (or methods) in your threads. You can use >the thread identity provided by Jython to select a network >connection in your output functions. > >You could even replace >sys.stdout and sys.stderr by objects doing precisely that, >(make sure to synchronize though, see below). >Have a look at console.py in the jython distribution for >an example of stream redirection. > >Of the top of my head: > >import thread > >def threadIdentity(): > return thread.currentThread() # or something like this, see the python docs. > >import threading > >class OutputRedirectByThread: > def __init__(self): > self.networkStreamByThread = {} > self.sema = threading.semaphore() # might not be needed > > def startRedirectingThreadOutput(networkOutputStream): > self.networkStreamdByThread[threadIdentity()] = networkOutputStream > > def write(self, s): > self.sema.acquire() > try: self.networkStreamByThread[threadIdentity()].write(s) > finally: self.sema.release() > > def flush(self): > self.sema.acquire() > try: self.networkStreamByThread[threadIdentity()].flush() > finally: self.sema.release() > >Create an object of this class, use it to replace sys.stdout and/or >sys.stderr, and call startRedirectingThreadOutput() just before invoking >the interpreter in the thread. > >Also you'll probably need stdin from the network connection too, >so a more elaborate design with stdin/stdout/stderr per thread >might be better. > >>If I try to 'set' a variable in one interpreter from another, the >>variable gets lost. > >Variables in module scope are 'one per process', because modules >are 'one per process'. If you change these, the changes are visible >in other threads. You'll probably need the threading module >to synchronize access to these. >Local function variables are 'one per thread', and invisible to >other threads. > >>Thanks in advance, > >My pleasure, > >Ype Kingma |