Coroutine singleThread MutiThread Mutiprocess (python3.8 环境)

Coroutine singleThread MutiThread Mutiprocess (python3.8 环境)

Flask 如何实现非阻塞 (写的很好)

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/

两次时间是一样的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值