百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Python的异步IO和协程详细解析(python的异步编程)

off999 2024-09-29 16:15 16 浏览 0 评论

IO模型

同步IO

  • 在IO过程中当前线程被挂起,当前线程其他需要CPU计算的代码无法执行
    • 一般的io是同步的
    • 多线程可解决该问题
  • 计算和IO任务可以由不同的线程负责
  • 但会带来线程创建、切换的成本,而且线程数不能无上限地增加

异步IO

当前线程只发出IO指令,但不等待其执行结束,而是先执行其他代码,避免线程因IO操作而阻塞

事件驱动模型

  • 一种编程范式,程序执行流由外部事件决定
  • 包含一个事件循环,当外部事件发生时使用回调机制来触发相应的处理
  • 可能的实现机制
    ? 每收到一个请求,创建一个新的进程来处理该请求;
    ? 每收到一个请求,创建一个新的线程来处理该请求;
    ? 每收到一个请求,放入一个事件列表让主进程通过非阻塞IO方式来处理请求
  • 一般场景
    当程序中有许多任务,任务之间高度独立(不需要互相通信或等待彼此等),并且在等待事件到来时,某些任务会阻塞

事件列表模型

  • 主线程不断重复“读取请求-处理请求”这一过程– 进行IO操作时相关代码只发出IO请求,不等待IO结果,然后直接结束本轮事件处理,进入下一轮事件处理
  • 当IO操作完成后,将收到IO完成消息,在处理该消息时再获取IO操作结果
  • 在发出IO请求到收到IO完成消息期间,主线程并不阻塞,而是在循环中继续处理其他消息
  • 对于大多数<font color='red'>IO密集型</font>的应用程序,使用<font color='red'>异步IO</font>将大大提升系统的多任务处理能力

协程

  • Coroutine,peusdo-thread,micro-thread
  • “微线程”
  • 在一个线程中会有很多函数,一般将这些函数称为子程序,在子程序执行过程中可以中断去执行别的子程序,而别的子程序也可以中断回来继续执行之前的子程序,这个过程就称为协程 执行函数A时,可以随时中断,进而执行函数B,然后中断B并继续执行A,且上述切换是自主可控的 但上述过程并非函数调用(没有调用语句)
  • 表象上类似多线程,但协程本质上只有一个线程在运行

Event Loop

  • The event loop is running in a thread
  • It gets tasks from the queue
  • Each task calls the next step of a coroutine
  • If coroutine calls another coroutine (await
    <coroutine_name>), the current coroutine gets suspended and context switch occurs. Context of the current coroutine (variables, state) is saved and context of a called coroutine is loaded
  • If coroutine comes across a blocking code (I/O, sleep), the current coroutine gets suspended and control is passed back to the event loop
  • Event loop gets next tasks from the queue 2, …n
  • Then the event loop goes back to task 1 from where it left off

协程的优点

  • 无需线程上下文切换的开销,协程避免了无意义的调度,由此可以提高性能
  • 无需原子操作锁定及同步的开销
  • 方便切换控制流,简化编程模型
    ? 线程由操作系统调度,而协程则是在程序级别由程
    序员自己调度
  • 高并发+高扩展性+低成本
    ? 一个CPU可以支持上万协程
    ? 在高并发场景下的差异会更突出

协程的缺点

  • 程序员必须自己承担调度的责任
  • 协程仅能提高IO密集型程序的效率,但对于CPU密集型程序无能为力
  • Python2和Python3中实现有一定差别
    ? 所用模块有区别
    ? 相关生态还在不断成熟
  • 在CPU密集型程序中要充分发挥CPU利用率需要结合多进程和协程

协程的实现

  • 生成器的send()函数
    ? 与next()作用类似,但可以发送值给对应的yield表达式
    ? 支持外部程序与生成器的交互
  • next(g)就相当于g.send(None)
  • 注意第一次调用next()或send(None)相当于启动生成器,不能使用send()发送一个非None的值
    ? 利用装饰器来解决该问题
    ? 在装饰器中先调用一次next
def gtest():
    print('step-1')
    x=yield 1
    print(x)
    print('step-2')
    y=yield 2
    print(y)
    print('step-3')
    x=yield 3

g=gtest()
#print(next(g))
#print(next(g))
#print(next(g))

print(g.send(None))
print(g.send('x=test'))
print(g.send('y=test'))

第一次启动生成器,必须send(None)
之后按序输出

step-1
1
x=test
step-2
2
y=test
step-3
3
import functools

def next_deco(func):
    @functools.wraps(func)
    def wrapper(*args,**kwargs):
        resulted_g=func(*args,**kwargs)
        next(resulted_g)  #在装饰器中先调用一次next
        return resulted_g
    return wrapper

@next_deco
def food_factory():
    food_list = []
    while True:
        food = yield food_list
        food_list.append(food)
        print("We have ",food_list)

fg=food_factory()
#fg.send(None)
fg.send('apple')
fg.send('banana')
fg.send('pear')
fg.send('orange')

yield food_list,所以会输出food_list的值,同时send的消息会返回到food中,并再次添加给food_list

We have  ['apple']
We have  ['apple', 'banana']
We have  ['apple', 'banana', 'pear']
We have  ['apple', 'banana', 'pear', 'orange']

通过gevent实现协程

  • 基于greenlet
  • spawn构建新协程
  • monkey.pach_all将第三方库标记为IO非阻塞
  • 通过协程池控制协程数目
import gevent

def foo():
    print('running in foo')
    gevent.sleep(2)#模拟io
    print('com back from bar in to foo')
    return 'foo'

def bar():
    print('running in bar')
    gevent.sleep(1)#模拟io
    print('com back from foo in to bar')
    return 'bar'

def func():
    print('in func of no io')
    return 'func'

def fund():
    print('in fund of no io')
    return 'fund'

jobs=[gevent.spawn(foo),gevent.spawn(bar),gevent.spawn(func),gevent.spawn(fund)]
gevent.joinall(jobs)
for job in jobs:
    print(job.value) #能够保证返回的顺序

首先按foo,bar,func,fund的顺序执行
在foo中遇到两秒阻塞,迅速执行bar,遇到一秒阻塞,迅速执行func和fund。
结束之后bar的一秒阻塞首先结束,执行之后语句,最后执行foo的剩余语句。
最后的返回结果gevent可以保证返回顺序。

running in foo
running in bar
in func of no io
in fund of no io
com back from foo in to bar
com back from bar in to foo
foo
bar
func
fund
import gevent
from gevent import socket   #asyncio

urls=['www.apple.com.cn','www.buaa.edu.cn','www.google.com','www.baidu.com']
jobs=[gevent.spawn(socket.gethostbyname,url) for url in urls]
gevent.joinall(jobs,timeout=10)
for url,ip in zip(urls,[job.value for job in jobs]):
    print('{}\t{}'.format(url,ip))

可以顺序输出结果,获取网址的ip

www.apple.com.cn        210.192.117.229
www.buaa.edu.cn 10.212.30.215 
www.google.com  31.13.72.1    
www.baidu.com   220.181.38.149

通过asyncio实现协程

  • python3.4引入 – 用asyncio提供的@asyncio.coroutine将任务标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作
  • Python3.5开始引入了async和await进一步
    简化语法
    ? 把@asyncio.coroutine替换为async
    ? 把yield from替换为await
  • Python3.7进一步变化…
import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main_1():
    print(f"started at {time.strftime('%X')}")

    await say_after(2, 'hello')
    await say_after(1, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main_1())

async def main_2():
    task1 = asyncio.create_task(
        say_after(2, 'hello'))

    task2 = asyncio.create_task(
        say_after(1, 'world'))

    print(f"started at {time.strftime('%X')}")

    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main_2())

函数1保证输出顺序,函数2不保证输出顺序。

started at 14:41:00
hello
world
finished at 14:41:03
started at 14:41:03
world
hello
finished at 14:41:05
import asyncio
import random

async def get_page(url,i):
    #print("start visit {}".format(url))
    await asyncio.sleep(random.randint(1,10))#nio
    #print("get the html page")
    return i

def print_status(future):#指定回调函数,运行结束后马上处理
    print("%s" % future.result(),end=' ')

if __name__=='__main__':
    loop=asyncio.get_event_loop()
    tasks=[]
    for i in range(100):
        tasks.append(loop.create_task(get_page('www.baidu.com/',i)))
    for task in tasks:
        task.add_done_callback(print_status)#注意与执行顺序的不同,等所有任务执行结束后再获取结果
    loop.run_until_complete(asyncio.wait(tasks))
    
    print()
    
    for task in tasks:
        print(task.result(),end=' ')

    print()

指定运行结束之后马上处理的回调函数,输出按照实际运行顺序输出。
未指定的按照顺序输出loop

8 25 27 57 52 98 99 17 43 89 84 36 59 14 23 46 41 71 13 12 97 44 87 21 39 83 76 78 7 35 33 62 54 5 91 90 42 82 1 68 29 95 28 
50 93 10 40 80 3 69 32 64 60 56 4 45 85 18 75 15 20 88 81 38 74 37 34 65 86 48 51 24 72 96 19 63 31 30 16 6 49 61 26 22 9 58 
79 92 70 55 73 47 67 94 11 66 2 77 0 53 

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

通过aiofiles实现文件的异步读写

pip install aiofiles
async with aiofiles.open(path,mode='r') as f: contents = await f.read()

相关推荐

Python钩子函数实现事件驱动系统(created钩子函数)

钩子函数(HookFunction)是现代软件开发中一个重要的设计模式,它允许开发者在特定事件发生时自动执行预定义的代码。在Python生态系统中,钩子函数广泛应用于框架开发、插件系统、事件处理和中...

Python函数(python函数题库及答案)

定义和基本内容def函数名(传入参数):函数体return返回值注意:参数、返回值如果不需要,可以省略。函数必须先定义后使用。参数之间使用逗号进行分割,传入的时候,按照顺序传入...

Python技能:Pathlib面向对象操作路径,比os.path更现代!

在Python编程中,文件和目录的操作是日常中不可或缺的一部分。虽然,这么久以来,钢铁老豆也还是习惯性地使用os、shutil模块的函数式API,这两个模块虽然功能强大,但在某些情况下还是显得笨重,不...

使用Python实现智能物流系统优化与路径规划

阅读文章前辛苦您点下“关注”,方便讨论和分享,为了回馈您的支持,我将每日更新优质内容。在现代物流系统中,优化运输路径和提高配送效率是至关重要的。本文将介绍如何使用Python实现智能物流系统的优化与路...

Python if 语句的系统化学习路径(python里的if语句案例)

以下是针对Pythonif语句的系统化学习路径,从零基础到灵活应用分为4个阶段,包含具体练习项目和避坑指南:一、基础认知阶段(1-2天)目标:理解条件判断的逻辑本质核心语法结构if条件:...

[Python] FastAPI基础:Path路径参数用法解析与实例

查询query参数(上一篇)路径path参数(本篇)请求体body参数(下一篇)请求头header参数本篇项目目录结构:1.路径参数路径参数是URL地址的一部分,是必填的。路径参...

Python小案例55- os模块执行文件路径

在Python中,我们可以使用os模块来执行文件路径操作。os模块提供了许多函数,用于处理文件和目录路径。获取当前工作目录(CurrentWorkingDirectory,CWD):使用os....

python:os.path - 常用路径操作模块

应该是所有程序都需要用到的路径操作,不废话,直接开始以下是常用总结,当你想做路径相关时,首先应该想到的是这个模块,并知道这个模块有哪些主要功能,获取、分割、拼接、判断、获取文件属性。1、路径获取2、路...

原来如此:Python居然有6种模块路径搜索方式

点赞、收藏、加关注,下次找我不迷路当我们使用import语句导入模块时,Python是怎么找到这些模块的呢?今天我就带大家深入了解Python的6种模块路径搜索方式。一、Python模块...

每天10分钟,python进阶(25)(python进阶视频)

首先明确学习目标,今天的目标是继续python中实例开发项目--飞机大战今天任务进行面向对象版的飞机大战开发--游戏代码整编目标:完善整串代码,提供完整游戏代码历时25天,首先要看成品,坚持才有收获i...

python 打地鼠小游戏(打地鼠python程序设计说明)

给大家分享一段AI自动生成的代码(在这个游戏中,玩家需要在有限时间内打中尽可能多的出现在地图上的地鼠),由于我现在用的这个电脑没有安装sublime或pycharm等工具,所以还没有测试,有兴趣的朋友...

python线程之十:线程 threading 最终总结

小伙伴们,到今天threading模块彻底讲完。现在全面总结threading模块1、threading模块有自己的方法详细点击【threading模块的方法】threading模块:较低级...

Python信号处理实战:使用signal模块响应系统事件

信号是操作系统用来通知进程发生了某个事件的一种异步通信方式。在Python中,标准库的signal模块提供了处理这些系统信号的机制。信号通常由外部事件触发,例如用户按下Ctrl+C、子进程终止或系统资...

Python多线程:让程序 “多线作战” 的秘密武器

一、什么是多线程?在日常生活中,我们可以一边听音乐一边浏览新闻,这就是“多任务处理”。在Python编程里,多线程同样允许程序同时执行多个任务,从而提升程序的执行效率和响应速度。不过,Python...

用python写游戏之200行代码写个数字华容道

今天来分析一个益智游戏,数字华容道。当初对这个游戏颇有印象还是在最强大脑节目上面,何猷君以几十秒就完成了这个游戏。前几天写2048的时候,又想起了这个游戏,想着来研究一下。游戏玩法用尽量少的步数,尽量...

取消回复欢迎 发表评论: