一個python線程池的源碼解析,python線程源碼
python為了方便人們編程高度封裝了很多東西,比如進程裡的進程池,大大方便了人們編程的效率,但是預設卻沒有線程池,本人前段時間整理出一個線程池,並進行了簡單的解析和注釋,本人水平有限,如有錯誤希望高手指點,願與君共同學習與進步,廢話少說,上源碼
import threading,time,queuestop = object()class Thread(object): def __init__(self,max_num):#建構函式 self.q = queue.Queue() #建立一個隊列,存放任務 self.max_num = max_num #線程池最大線程數 self.terminal = False self.generate_list = [] #真實建立的線程列表 self.free_list = [] #空閑線程列表 def generate_thread(self): #建立進程並執行的函數 t = threading.Thread(target = self.call) t.start() def call(self): #擷取任務並且執行任務函數 current_thread = threading.currentThread #擷取當前線程 self.generate_list.append(current_thread) #加入列表 even = self.q.get() #從隊列擷取到任務 while even != stop:#在有 任務 的情況下迴圈執行任務 func,args,callback = even try: ret = func(args) #執行函數 status = True except Exception as e: #如果有錯誤status為假,執行結果fu賦值ret status = False ret = e if callback is not None:#判斷如果沒有回呼函數 try: callback(status,ret) except Exception as e: pass if self.terminal: #p判斷是否終止 even = stop else: self.free_list.append(current_thread) #執行完畢將線程加入空閑 even = self.q.get() #再次擷取 self.free_list.remove(current_thread)#修改狀態為非閑置 else: self.generate_list.remove(current_thread)#如果沒有任務,會刪除真實建立的線程列表中的元素 def run(self, func, args, callback=None): # 線程池啟動並執行方法 w = (func, args, callback,) self.q.put(w) # 將任務放進隊列 if len(self.free_list) == 0 and len(self.generate_list) < self.max_num:#判斷是否建立線程 self.generate_thread() def close(self): #關閉線程函數 num = len(self.generate_list) while num: self.q.put(stop) num -= 1 def terminal(self): #一個可以在任務沒執行完的情況下強制終止的函數, self.terminal = True# 根據 self.terminal判斷 max_num = len(self.generate_list) while max_num: #放入列表長度的個數的stop結束正在阻塞的進程 self.q.put(stop) max_num -= 1#該方法清空了線程但是沒清空隊列任務 def terminall(self): # 一個可以在任務沒執行完的情況下強制終止的函數, self.terminal = True # 根據 self.terminal判斷 while self.generate_list:#如果列表不為空白就會不斷放入sotp清空線程列表 self.q.put(stop) self.q.empty()#線程清空完畢之後清空隊列,完美。def work(a): #以下為樣本 print(a)pool = Thread(10)for i in range(50): pool.run(func=work,args=i)pool.close()