python中使用threading模块实现多线程
参数 :
target 线程函数
args 以元组方式给线程函数传参
kwargs 以字典方式给线程函数传参
name 线程名称 (默认Thread-1)
返回值 : 返回线程对象
from threading import Thread
def fun1(a,b):
x=a+b
return x
t1=Thread(target=fun1,args=(1,2))
t2=Thread(target=fun1,args=(3,4))
t1.daemon = True #该属性默认为False 主线程执行完毕不会影响其他线程的执行,如果设置为True 则主线程执行完毕其他线程也终止执行
print(t1.is_alive())#线程状态
print(t1.name)#线程名称
t1.start()#启动线程
t2.start()
t1.join()#阻塞等待线程回收
t2.join()
线程池
python中使用threadpool模块创建线程池
import threadpool
def fun(x):
return x**2
lst=[i for i in range(10)]
pool = threadpool.ThreadPool(5)#在线程池中创建5个线程
req=threadpool.makeRequests(fun,lst) #生成一个要执行的函数队列,将lst中的参数依次传递给函数fun
for r in req: #将要执行的函数依次放入线程池中
pool.putRequest(r)
pool.wait() #等待执行完毕回收线程池