[Python] python实现线程池 →→→→→进入此内容的聊天室

来自 , 2019-04-08, 写在 Python, 查看 137 次.
URL http://www.code666.cn/view/a709909b
  1. import threading
  2. import time
  3. import signal
  4. import os
  5.  
  6. class task_info(object):
  7.     def __init__(self):
  8.         self.func = None
  9.         self.parm0 = None
  10.         self.parm1 = None
  11.         self.parm2 = None
  12.    
  13. class task_list(object):
  14.     def __init__(self):
  15.         self.tl = []
  16.         self.mutex = threading.Lock()
  17.         self.sem = threading.Semaphore(0)
  18.    
  19.     def append(self, ti):
  20.         self.mutex.acquire()
  21.         self.tl.append(ti)
  22.         self.mutex.release()
  23.         self.sem.release()
  24.    
  25.     def fetch(self):
  26.         self.sem.acquire()
  27.         self.mutex.acquire()
  28.         ti = self.tl.pop(0)        
  29.         self.mutex.release()
  30.         return ti
  31.    
  32. class thrd(threading.Thread):
  33.     def __init__(self, tl):
  34.         threading.Thread.__init__(self)
  35.         self.tl = tl
  36.    
  37.     def run(self):
  38.         while True:
  39.             tsk = self.tl.fetch()
  40.             tsk.func(tsk.parm0, tsk.parm1, tsk.parm2)    
  41.  
  42. class thrd_pool(object):
  43.     def __init__(self, thd_count, tl):
  44.         self.thds = []
  45.        
  46.         for i in range(thd_count):
  47.             self.thds.append(thrd(tl))
  48.    
  49.     def run(self):
  50.         for thd in self.thds:
  51.             thd.start()
  52.            
  53.            
  54. def func(parm0=None, parm1=None, parm2=None):
  55.     print 'count:%s, thrd_name:%s'%(str(parm0), threading.currentThread().getName())
  56.    
  57. def cleanup(signo, stkframe):
  58.     print ('Oops! Got signal %s', signo)  
  59.    
  60.     os._exit(0)
  61.    
  62. if __name__ == '__main__':
  63.    
  64.     signal.signal(signal.SIGINT, cleanup)
  65.     signal.signal(signal.SIGQUIT, cleanup)
  66.     signal.signal(signal.SIGTERM, cleanup)
  67.    
  68.     tl = task_list()
  69.     tp = thrd_pool(6, tl)
  70.     tp.run()
  71.    
  72.     count = 0
  73.     while True:
  74.        
  75.         ti = task_info()
  76.         ti.parm0 = count
  77.         ti.func = func
  78.         tl.append(ti)
  79.         count += 1
  80.        
  81.         time.sleep(2)
  82.     pass
  83.  
  84.  
  85.  
  86.  
  87. #//python/5169

回复 "python实现线程池"

这儿你可以回复上面这条便签

captcha