1、通過threading.BoundedSemaphore,這種方法是分批灌線程,分批執行,等所有線程灌完了才會執行最后的print
# -*- coding:utf-8 -*- import threading import time class Test(threading.Thread): def __init__(self): threading.Thread.__init__(self) def printthread(self): print self.name, "-->進程創建" time.sleep(2) print self.name, "-->進程結束" threadmax.release() def run(self): self.printthread() #要執行的函數 if __name__ =='__main__': threadmax = threading.BoundedSemaphore(3) # 限制1次裝載3個線程 threads=[] for a in range(5): threadmax.acquire() a=Test() threads.append(a) a.start() print("=============") # 需要等到線程全部裝載完了才會打印這一行
2、使用threading.Semaphore(),這種感覺是一次性灌所有線程,但是分批執行,不阻塞下面的代碼
# -*- coding:utf-8 -*- import threading,Queue from time import sleep class Test(threading.Thread): def __init__(self, lock, num): threading.Thread.__init__(self) self.lock = lock self.num = num def ThreadTest(self): # print(self.name, "-->start") sleep(2) # print(self.name, "-->finished") def run(self): with self.num: # 同時並行指定的線程數量,執行完畢一個則死掉一個線程 # 以下為需要重復的單次函數操作 lock.acquire() # 鎖住線程,防止同時輸出造成混亂 print u"現有", threading.enumerate() lock.release() self.ThreadTest() if __name__ == "__main__": threads=[] lock=threading.Lock() queue=Queue.Queue() num=threading.Semaphore(3) # 設置同時執行的線程數為3,其他等待執行 # 啟動所有線程 for i in range(8): # 總共需要執行的次數 t=Test(lock,num) t.start() threads.append(t) print '所有執行完畢'
還可以使用multiprocessing的線程池
from multiprocessing.dummy import Pool async_pool = Pool(200) # 控制200個線程並發 class test(): def __init__(self, server_list): self.server_list = server_list def domainthing(self): pass def run(self): # 使用map一次性灌如線程 result = async_pool.map_async(domainthing, server_list) result.wait() # 等待所有進程函數執行完畢 # async_pool.close() # 關閉pool,使其不在接受新的任務 # async_pool.join() # 主進程阻塞,等待子進程的退出, join方法要在close或terminate之后使用。 # 每次灌一個 for iten in server_list: result = async_pool.apply_async(domainthing, (iten, )) # async_pool.close() # 關閉pool,使其不在接受新的任務 # async_pool.join() # 主進程阻塞,等待子進程的退出, join方法要在close或terminate之后使用。 if __name__ = "__main__": server_list = [{"id": 1}, {"id": 2}] test(server_list)