微慑信息网

python 线程池ThreadPoolExecutor操作测试

先贴上代码:

#coding:utf-8
from concurrent.futures import ThreadPoolExecutor,as_completed
import requests
import time

def getHtmllen(url):
    res =  requests.get(url).text
    mlen =len(res)
    return  url,mlen
def start():
    urls = []
    for i in range(435194,435194-20,-1):
        url='http://****/archives/%d.html' % i
        urls.append(url)
    start =time.time()
    '''
    with ThreadPoolExecutor() as pool:
        results = pool.map(getHtmllen,urls)
        for result in results:
            print (result)
    end = time.time()
    print ('cost time is :',end -start)
    '''
    with ThreadPoolExecutor() as pool:
        futures = [pool.submit(getHtmllen, url) for url in urls]
        for future in futures:
            print(future.result())
        #for future in as_completed(futures):
            #print (future.result())
    end = time.time()
    print ("cost times is :",end-start)

def main():
    start()
if __name__ == '__main__':
    main()

其中涉及到2种方式进行线程池操作:

1、

    with ThreadPoolExecutor() as pool:
        results = pool.map(getHtmllen,urls)
        for result in results:
            print (result)

 

2、

    with ThreadPoolExecutor() as pool:
        futures = [pool.submit(getHtmllen, url) for url in urls]
        for future in futures:
            print(future.result())
        #for future in as_completed(futures):
            #print (future.result())

第二种中,有2种方式展示结果,分别为:

按照顺序打印:

for future in futures:
            print(future.result())

乱序打印:

 #for future in as_completed(futures):
            #print (future.result())

注:1、使用map函数,简单;2、future模式更强大

赞(0) 打赏
转载请附本站链接,未经允许不得转载,,谢谢:微慑信息网-VulSee.com » python 线程池ThreadPoolExecutor操作测试

评论 抢沙发

微慑信息网 专注工匠精神

微慑信息网-VulSee.com-关注前沿安全态势,聚合网络安全漏洞信息,分享安全文档案例

访问我们联系我们

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册