在python中多线程可以使用threading来实现,但实际使用时考虑性能等,大多会使用到线程池,下面就是基于python2和python3来说明下线程池的使用。
import time
def testthread(fl):
time.sleep(1)
print("print:"+fl)
return fl
python2
from multiprocessing import Pool #引入pool
lst = [] #参数列表
pool = Pool(3) #设定线程池大小
pool.map(testthread, lst) #设置执行的函数及参数
pool.close() #禁止吸入线程池
pool.join() #开始执行
python3
from concurrent.futures import ThreadPoolExecutor, as_completed #引入
lst = [] #参数列表
executor = ThreadPoolExecutor(max_workers=3) #设置线程池大小
all_task = [executor.submit(testthread, (fl)) for fl in lst] #设置线程执行的函数及参数
for future in as_completed(all_task): #执行线程
data = future.result() #等待执行方法的返回值,便于后续处理
个人使用下来感觉python3的线程池好一点,但python2的应用比较广,在无法更新python版本的情况下,也只能用python2的方法搞定。