Coroutine singleThread MutiThread Mutiprocess (python3.8 环境)
os.getpid()
获取当前进程 id
threading.current_thread().name
获取线程名字
time.sleep(3)
休眠当前线程,模拟 IO,不影响其他线程
await asyncio.sleep(3)
协程休眠,模拟 IO,主线程可以去执行其他协程
协程
import asyncio
import threading
import os
from aiohttp import web
routes = web.RouteTableDef()
@routes.get('/')
async def index(request):
# 耗时的io操作
await asyncio.sleep(6)
text = 'pid %d , <br> threading %s <br> request %d ' % (
os.getpid(), threading.current_thread().name, id(request))
return web.Response(body=text, content_type='text/html')
app = web.Application()
app.add_routes(routes)
web.run_app(app, host='127.0.0.1', port=6060)
单线程,多线程,多进程
import time
import threading
import os
from flask import Flask, request
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
time.sleep(7)
text = 'pid %d , <br> threading %s <br> request %d ' % (
os.getpid(), threading.current_thread().name, id(request))
return text
if __name__ == '__main__':
# 多进程
app.run(host="127.0.0.1", port=8000, processes=4, threaded=False)
# 多线程
app.run(host="127.0.0.1", port=8000, threaded=True)
# 单线程,process默认为1
app.run(host="127.0.0.1", port=8080, threaded=False)
结果
多进程、多线程、协程 在不同浏览器都访问相同的 router 不阻塞。
多进程、多线程、协程、单线程 在相同浏览器都访问相同的 router 都阻塞。
不同的 router 怎么样都不阻塞,除了在单线程的情况下。
原因
浏览器搞的鬼,浏览器判断为同样的 request 后,上一个 request 请求返回后才继续请求。有一个队列。
证明
wget http://127.0.0.1:8000/
wget http://127.0.0.1:8000/
两次时间是一样的