問題:1-100個數多線程打印
import threadpool def pool_num(num,p_methond,num_list): pool=threadpool.ThreadPool(num) #聲明線程池個數 reqs=threadpool.makeRequests(p_methond,num_list) #生成線程池啟動參數 [pool.putRequest(req) for req in reqs] #循環執行啟動線程 pool.wait() #等待子線程 def p_methond(num): print(num) num_list=[i for i in range(1,101)] pool_num(3,p_methond,num_list)
問題:1-100個數,線程數可以自定義,然后多線程打印這1-100個數,要求每個線程打印的數分段連續打印,比如說用2個線程,那么線程1是打印1-50,線程2是打印51-100
線程方式實現
import threading def func(arg): #打印數字函數 for i in arg: print("當前線程:", threading.currentThread().name, "----", i+1) def thread_num(total,num): #傳參是打印數字的總數及線程數 data = [x for x in range(0, total)] #所有的數字循環放入list split_data = [data[i: i + int(total/num)] for i in range(0, len(data), int(total/num))] #帶步長的循環list,且每段放入一個list,生成2維數組 for d in split_data: #循環二維數組,每次取一個數組,作為打印函數的傳參 t = threading.Thread(target=func, args=(d,)) #生成線程且調用方法及給予傳參 t = t.start()#啟動線程 while threading.active_count()!=1: #等待子線程 pass thread_num(13,2) #調用線程方法
numpy模塊分段:
import threading import numpy def func(arg): for i in arg: print(threading.currentThread().name, "----", i+1) def thread_num(total,num): result=numpy.array_split(range(total),num) #分段 for i in result: t=threading.Thread(target=func,args=(i,)) #聲明線程 t.start() #啟動線程 while threading.active_count()!=1: #等待子線程 pass
隨記:問題--為什么等子線程
開了幾個線程執行任務,如果不等待線程, 如果你的進程掛了的時候,線程也會掛掉
還有一個場景, 如果你要等待所有線程處理完后的結果,那就必須等待了