我们在做一些数据爬取时,会使用多线程来提高爬取的效率。但是过多的线程,会导致被爬取的服务器,对IP进行限制甚至封禁,为了避免这种情况,我们需要限制同一时间启用的线程数量,而存储同一时间启用线程是容器,我们成为线程池。
现在实现线程池的框架,我们一般使用threadpool框架。
threadpool安装:
使用
pip install threadpool
简单的实例:
import threadpool
import time
pool = threadpool.ThreadPool(2)
def run(x):
print("running x", x)
time.sleep(2)
requests = threadpool.makeRequests(run, [x for x in range(30)]);
[pool.putRequest(req) for req in requests]
pool.wait()
你会发现,在同一时间只有两个进程在跑,其他的进程都在等待。