2008/08/25

Examples of Python threading and Queue

#!/usr/bin/env python
import threading,Queue,random,time,sys

class th(threading.Thread):

def __init__(self,threadName,queue):
threading.Thread.__init__(self,name=threadName)
self.name=threadName
self.Q=queue
print 'Name: %s started.'%(self.getName())

def run(self):
while 1:
num=self.Q.get(1)
if num==-1:
self.Q.task_done()
break
else:
print '%s sleep %f'%(self.name,num)
time.sleep(num)
print '%s wake after %f'%(self.name,num)
self.Q.task_done()
print '%s finish.'%self.name

thnum=2
Q=Queue.Queue(thnum*2)
for t1 in range(thnum):
th('thread%d'%t1,Q).start()

for t1 in range(10):
Q.put(random.random(),1)

for t1 in range(thnum):
Q.put(-1,1)
print 'wait...'
Q.join()


Do not forget to call Q.task_done() after each run of thread. Otherwise, Q.join() will be waiting for ever.

No comments: