Entry
Searching an example that has multiple threads write to the Queue object?
Dec 8th, 2001 17:30
Matthew King, unknown unknown, Robert W. Bill
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 = self.q.get() # this blocks--see Python Library Ref
# you may want get_nowait() in try/except
print logEntry
def main():
q = Queue(10)
logger(q).start()
for i in range(10):
clientThread(q,i).start()
if __name__=='__main__':
main()