python3-线程池

 

from flask import Flask,render_template
from time import sleep

# 实例化一个app
app = Flask(__name__)
#创建视图函数和路由地址
@app.route('/bobo')
def index1():
    sleep(2)
    return 'hello bobo'

@app.route('/jay')
def index2():
    sleep(3)
    return render_template('test.html')

@app.route('/tom')
def index3():
    sleep(3)
    return render_template('test.html')

if __name__ == '__main__':
    app.run(debug=True)

 

import time
from multiprocessing.dummy import Pool
import requests

urls = [
    'http://127.0.0.1:5000/bobo',
    'http://127.0.0.1:5000/jay',
    'http://127.0.0.1:5000/tom',
]
def get_request(url):
    page_text = requests.get(url=url).text
    return len(page_text)

#同步代码
if __name__ == "__main__":
    start=time.time()
    for url in urls:
        res = get_request(url)
        print(res)
    print('总耗时:',time.time()-start)


# 异步代码
if __name__ == "__main__":
    start=time.time()
    pool = Pool(3) #开启线程的数量
    #使用get_request作为回调函数,需要基于异步的形式对urls列表中的每一个元素进行操作
    #保证回调函数必须要有一个参数和返回值
    result_list = pool.map(get_request,urls)
    print(result_list)
    print('总耗时:',time.time()-start)

posted on 2022-11-11 14:48  Colin88  阅读(49)  评论(0编辑  收藏  举报