Heim > Fragen und Antworten > Hauptteil
thread_list = []
for kw_do in exc_kw():
thread_list.append(Thread(target=zz_kw,args=(kw_do,)))
for thread in thread_list:
thread.start()
for thread in thread_list:
thread.join()
这样运行会卡死,请问怎样控制5个线程或者10个线程呢?
大家讲道理2017-04-17 17:59:54
pool = threadpool.ThreadPool(poolSize)
poolSize这里来控制线程数量
import threadpool
import requests
def get_url(url):
r = requests.get(url)
return url, r.status_code
def print_result(request, result):
print result
urls = [
'http://www.baidu.com',
'http://www.jd.com',
'http://www.taobao.com',
'https://segmentfault.com',
'http://www.baidu.com',
'http://www.jd.com',
'http://www.taobao.com',
'https://segmentfault.com',
'http://www.baidu.com',
'http://www.jd.com',
'http://www.taobao.com',
'https://segmentfault.com'
]
pool = threadpool.ThreadPool(5)
for th in threadpool.makeRequests(get_url, urls, print_result):
pool.putRequest(th)
pool.wait()
迷茫2017-04-17 17:59:54
你的问题大概是当任务多的时候线程会非常多。换一个思路看这个问题,使用一个线程,设置为5个或10个,然后把任务丢到线程池就好了,参考 python ThreadPoolExecutor 的用法。