首页 > python3.5怎样控制线程的数量呢?

python3.5怎样控制线程的数量呢?

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个线程呢?


建议使用多进程来尝试是不是也会出现卡死现象!
尝试找下卡死原因,而不是马上去控制线程数量来隐藏这个卡死问题!


你的问题大概是当任务多的时候线程会非常多。换一个思路看这个问题,使用一个线程,设置为5个或10个,然后把任务丢到线程池就好了,参考 python ThreadPoolExecutor 的用法。


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://.com',
    'http://www.baidu.com',
    'http://www.jd.com',
    'http://www.taobao.com',
    'https://.com',
    'http://www.baidu.com',
    'http://www.jd.com',
    'http://www.taobao.com',
    'https://.com'
]

pool = threadpool.ThreadPool(5)

for th in threadpool.makeRequests(get_url, urls, print_result):
    pool.putRequest(th)

pool.wait()
【热门文章】
【热门文章】