[Tutor] demon / app I/F better way ?

Kent Johnson kent37 at tds.net
Sun Nov 14 18:20:37 CET 2004


I would put make a class to hold the demon thread. The main program can 
create the queue and pass it to the demon. Here is a simple example of a 
Worker thread that passes work back to a main program:

from threading import Thread
from Queue import Queue, Empty
from time import sleep

class Worker(Thread):
     ''' Every two seconds put some work in the queue '''
     def __init__(self, queue):
         Thread.__init__(self)
         self.queue = queue
         self.setDaemon(True)

     def run(self):
         while True:
             self.queue.put('Work')
             sleep(2)


def main():
     fifo = Queue()
     Worker(fifo).start()

     # Monitor the work queue from the Worker thread
     while True:
         sleep(0.5)
         try:
             work = fifo.get(False)
             print work
         except Empty:
             print 'Nothing to do'

main()


Kent

Dave S wrote:
> Kent Johnson wrote:
> 
>> Dave S wrote:
> ...mmm ... Now I have an idea as to what sockets are, I like threads to 
> :-), they seem OTT for what I need.
> 
> Having decided on threading the demon, and using a fifo, the queue 
> module looks cool, I have one last dilema. One that quite often causes 
> me problems, that scope, namespace thing ;-)
> 
> If I have my demon thread running, and I define a queue, it will work 
> fine, If I have my main app running and define a queue, it will also 
> work fine but this defines two seperate queues which are not joined, 
> data from one will not pass to the other.
> 
> If I were to define a seperate script which handles the queue 
> 'fifio.py'  & import it to both the deamon thread & the main app, this 
> would use the class definition as a king of global variable. Would this 
> be the best way ? - more importantly would it work :-D !
> 
> Dave
> 


More information about the Tutor mailing list