6 07年03月

改写地一个python利用Queue多线程干活的脚本

贝贝爸 发表在 原创技术文章 |

python用Queue多线程干活的脚本

  1. #!/usr/bin/env python
  2. import Queue 
  3. import threading 
  4. import time 
  5. import random  
  6.  
  7. q=Queue.Queue(0) 
  8. NUM_WORKERS = 3  
  9.  
  10. class MyThread(threading.Thread):
  11.     """A worker thread.""" 
  12.     def __init__(self, input, worktype):
  13.         self._jobq = input 
  14.         self._work_type = worktype 
  15.         threading.Thread.__init__(self) 
  16.     def run(self):
  17.         """ 
  18.         Get a job and process it.
  19.         Stop when there's no more jobs
  20.         """ 
  21.         while True:
  22.             if self._jobq.qsize()>0:
  23.                 job = self._jobq.get() 
  24.                 worktype=self._work_type 
  25.                 self._process_job(job,worktype) 
  26.             else:
  27.                 break 
  28.     def _process_job(self, job,worktype):
  29.         """ 
  30.         Do useful work here.
  31.         worktype: let this thread do different work
  32.         1,do list
  33.         2,do item
  34.         3,,,
  35.         """ 
  36.         doJob(job)  
  37.  
  38. def doJob(job):
  39.     """ 
  40.     do work function 1
  41.     """ 
  42.     time.sleep(random.random()*3) 
  43.     print "doing ",job 
  44. if __name__=='__main__':  
  45.  
  46.     print "begin..." 
  47.     #put some work to q
  48.     for i in range(NUM_WORKERS*2):
  49.         q.put(i) 
  50.     #print total job q's size
  51.     print "job q'size",q.qsize() 
  52.     #start threads to work
  53.     for x in range(NUM_WORKERS):
  54.         MyThread(q,x).start() 
  55.     #if q is not empty, wait
  56.     #while q.qsize()>0:
  57.     #    time.sleep(0.1)

相关文章

发表评论

美体小铺急救棒 the bodyshop body shop 美体小铺茶树精油 美体小铺接骨木花眼胶 美体小铺VE眼霜
15Q.0.609Ss.