需求:有100個數據,啓動5個線程,每一個線程分20個數據,怎麼把這20個數據分別傳給每一個線程。多線程
1. 利用多線程實現函數
import threading nums = list(range(100)) def p(nums): for num in numss: print(num) threads = [] for i in range(5): # nums[0:20] #每次取的值 # nums[20:40] # nums[40:60] # nums[60:80] # nums[80:] t = threading.Thread(target=p,args=(numss[i*20:(i+1)*20],)) t.start()
2. 利用線程池實現spa
import threadpool def p(num): print(num) res = list(range(100)) pool = threadpool.ThreadPool(20)#20個線程 reqs = threadpool.makeRequests(p,res)#生成線程要執行的全部線程,第一個參數爲函數名,第二個參數是傳的值 [pool.putRequest(req) for req in reqs] #列表生成式 pool.wait()#等待 其餘線程執行結束