python_线程池

线程池,比如我们有个方法要多线程运行1000次,我们不能声明1000个线程,这时候我们可以通过线程池设定50个线程,那么运行的时候就会自动分配给者1000次,也就是每个线程20次

如下例子就是线程池例子:

import requests,threading
import faker
import threadpool #线程池模块

f=faker.Faker(locale="zh-CN")
def down_load_file(url):
    r=requests.get(url) #get请求
    m=f.name() #随机生成文件名字
    with open('./pic/%s.jpg'%m,'wb') as fw: #图片二进制写入文件,保存为jpg格式
        fw.write(r.content)

url_list=[
            'http://www.nnzhp.cn/wp-content/uploads/2019/02/jiami.jpeg',
            'http://www.nnzhp.cn/wp-content/uploads/2019/03/js.png',
            'http://www.nnzhp.cn/wp-content/uploads/2018/08/ab389f04cb5b57344ef9655428bccaec.png'
        ]

pool=threadpool.ThreadPool(3)  #创建一个线程池,指定线程池最多有多少个线程

reqs=threadpool.makeRequests(down_load_file,url_list) #调用生成启动线程用的参数

[pool.putRequest(req) for req in reqs] #循环启动线程

print("当前的线程数",threading.activeCount()) #当前线程数,统计的线程数包括主线程

pool.wait() #等待子线程

print("测试结束") 
原文地址:https://www.cnblogs.com/xiaokuangnvhai/p/11279226.html