首頁  >  問答  >  主體

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

ringa_leeringa_lee2742 天前935

全部回覆(3)我來回復

  • 大家讲道理

    大家讲道理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()

    回覆
    0
  • 迷茫

    迷茫2017-04-17 17:59:54

    你的問題大概是當任務多的時候執行緒會非常多。換一個想法看這個問題,使用一個線程,設定為5個或10個,然後把任務丟到線程池就好了,參考 python ThreadPoolExecutor 的用法。

    回覆
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:59:54

    建議使用多重進程來嘗試是不是也會出現卡死現象!
    試著找下卡死原因,而不是馬上去控制線程數量來隱藏這個卡死問題!

    回覆
    0
  • 取消回覆