• 0
  • 0

python 线程池 threadpool 使用

2021-06-24 625 0 admin 所属分类:Python

通常调用线程的方式如下

1. 引入 线程模块

import threading

2.定义函数 

def download_file(data):
    print(data)

3.在线程中使用

threading.Thread(target=download_file, args=data).start()

使用起来方便 但是当处理多线程的时候没有办法设定最大线程个数,导致跑多线程会过度消耗系统资源,光耗带宽


线程池模快 threadpool

1 pip 安装

pip install threadpool

2 引入模块

import threadpool

3 构建线程池

pool = threadpool.ThreadPool(10) #这里创建10个线程的线程池

4 将所有需要在线程池跑的数据存到列表中 data 返回所有线程请求资源对象

reqs = threadpool.makeRequests(download_file , data)

5 构造列表表达式 依次将请求对象存储到线程池中 等待执行

[pool.putRequest(req) for req in reqs]

6 等待线程池执行完毕 ,继续后续业务

pool.wait()


想如果函数中需要多个参数对象的 建议data列表中可以存储字典对象 将所有需要用到的数据传入函数中执行 此时函数中data参数是字典

返回顶部