sample code of using Queue.

Robert W. Bill rbill at digisprings.com
Wed Jul 26 12:28:27 EDT 2000


Hi Sam,

If you hypothetically wanted to have one class log events from threads,
you could subclass threading.Thread and start with something that looks
like this:

from threading import *
from Queue import Queue

class clientThread(Thread):
    def __init__(self, q, myNumber):
	self.q = q
	self.myNumber = myNumber
	Thread.__init__(self)
			
    def run(self):
	# do something wacky #
	logline = "This is a log from thread #" + str(self.myNumber)
	self.q.put(logline) # this blocks--see Python Library Ref
			    # you may want to wrap in try/except
			    # with put_nowait

class logger(Thread):
    def __init__(self, q):
	self.q = q
	Thread.__init__(self)
	
    def run(self):
	print "logger started"
	# replace next line (range) with an event or something more 
	# useful
	for i in range(10):
	    logEntry = q.get() # this blocks--see Python Library Ref
			       # you may want get_nowait() in try/except
	    print logEntry

if __name__=='__main__':
    q = Queue(10)
    logger(q).start()
    for i in range(10):
	clientThread(q,i).start()


I realize this my not help too much with controlling the threads
lifespan.  Ask again when you get to the spot where you need some events,
joins or something to fine tune things.

-Robert


On Wed, 26 Jul 2000, Sam Wun wrote:

> I want to have multiple threads write to the Queue object.
> 
> Dose anyone has example for doing that? or could anyone point me to an url?
> 
> Thanks
> 
> Sam.
> 
> 
> 





More information about the Python-list mailing list