新老对比
用asyncio提供的@asyncio.coroutine可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作。为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法async和await,可以让coroutine的代码更简洁易读。请注意,async和await是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换:把@asyncio.coroutine替换为async;把yield from替换为await。
@asyncio.coroutine
def hello():
print("Hello world!")
r = yield from asyncio.sleep(1)
print("Hello again!")
async def hello():
print("Hello world!")
r = await asyncio.sleep(1)
print("Hello again!")
asyncio 和 EventLoop 的理解
asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。
asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。
消息循环机制
loop在很多框架模型都有,比如win的loop消息循环机制。安卓的主线程消息循环机制。
同样的EventLoop
内部就是一个死循环,可以接收传入的协程任务并执行。
测试加入协程运行
直接运行协程任务报错:
async def async_hello():
print("async Hello world!")
r = await asyncio.sleep(1)
print("async Hello again!")
if __name__ == '__main__':
async_hello()
异常信息:
C:/Users/huruwo/Desktop/work/sanic_test/async_await_learn.py:25: RuntimeWarning: coroutine 'async_hello' was never awaited
async_hello()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
必须使用await
修饰才能调用
改为
if __name__ == '__main__':
await async_hello()
还是报错
File "C:/Users/huruwo/Desktop/work/sanic_test/async_await_learn.py", line 25
await async_hello()
^
SyntaxError: 'await' outside function
因为使用了await 所以必须使用带了async的函数去调用。
卧槽 这不就形成了套娃吗
async函数需要使用await关键字调用
而await关键字又需要在async函数里才能使用
回过头看官方的示例代码:
loop = asyncio.get_event_loop()
#执行coroutine
loop.run_until_complete(hello())
loop.close()
使用event_loop运行协程函数
我们发现了需要获得一个loop来放入协程运行,修改我们的代码。
async def async_hello():
print("async Hello world!"+ str(int(time.time())))
r = await asyncio.sleep(1)
print("async Hello again!"+ str(int(time.time())))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
#执行coroutine
loop.run_until_complete(async_hello())
loop.close()
运行成功:
async Hello world!1612679437
async Hello again!1612679438
代码解释:
asyncio.get_event_loop() 获取asyncio的事件循环
loop.run_until_complete(async_hello()) 加入事件 保证运行到完成 run_until_complete
loop.close 关闭事件循环 (如果提前关闭将无法加入处理任何事件)
特意的 这里的sleep使用的asyncio.sleep
是协程的暂停而不是主线程的暂停。
event_loop是全局唯一的吗
是的 无论如何获取asyncio.get_event_loop()
的hash值都是相同的。
可以认定为同一个loop循环事件。
loop1 = asyncio.get_event_loop()
print('loop1 hash'+str(loop1.__hash__()))
#执行coroutine
loop2 = asyncio.get_event_loop()
print('loop2 hash'+str(loop2.__hash__()))
loop1 hash-9223371879467272032
loop2 hash-9223371879467272032
多个事件加入event_loop会如何
async def async_hello(s):
print("async Hello world!"+s +' '+ str(int(time.time())))
r = await asyncio.sleep(5)
print("async Hello again!"+s+ ' '+str(int(time.time())))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
tasks = [async_hello('task1'), async_hello('task2')]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
async Hello world!task1 1612680783
async Hello world!task2 1612680783
async Hello again!task1 1612680788
async Hello again!task2 1612680788
可以看出是并行的运行
顺便打印线程名字
async def async_hello(s,pause):
print("async Hello world!"+s +' '+str(threading.currentThread())+ str(int(time.time())))
r = await asyncio.sleep(pause)
print("async Hello again!"+s+ ' '+str(threading.currentThread())+str(int(time.time())))
async Hello world!task1 <_MainThread(MainThread, started 13952)>1612682755
async Hello world!task2 <_MainThread(MainThread, started 13952)>1612682755
async Hello again!task1 <_MainThread(MainThread, started 13952)>1612682757
async Hello again!task2 <_MainThread(MainThread, started 13952)>1612682760
可以看出来就是同一个主线程线程发出的操作。但是利用了协程在主线程做到了多个并发。也就是说协程做事情并没有额外的开辟新的线程,而是光速的切换了上下文。
所以即使访问主线程的全局变量也不会有任何异常。
协程和线程的关系
进程是系统进行资源分配和调度的独立单位;
线程是进程的实体,是CPU调度和分派的基本单位;
协程也是线程,称微线程,自带CPU上下文,是比线程更小的执行单元;
整个商店是一个进程
线程的服务模式:服务多少个客人就要多少个服务员
协程的服务模式:可以分化服务过程的事件个数 分给不同的服务员去做 你去找货 你去洗菜 你去收银 如果要保持顺序 就必须使用等待,否则无法拿到前面的结果。也就是await的 一个服务员可以飞快地转换身份 做不同的事情。
协程:是一种用户态的轻量级线程,协程的调度完全由用户控制。协程拥有自己的寄存器上下文和栈。 协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈,直接操作栈则基本没有内核切换的开销,可以不加锁的访问全局变量,所以上下文的切换非常快。
协程 task create_task add_done_callback
协程
首先定义一个协程,在def前加入async声明,就可以定义一个协程函数。一个协程函数不能直接调用运行,只能把协程加入到事件循环loop中。asyncio.get_event_loop方法可以创建一个事件循环,然后使用run_until_complete将协程注册到事件循环,并启动事件循环。例如: [python] view plain copy
import asyncio
async def fun():
print('hello word')
loop = asyncio.get_event_loop()
loop.run_until_complete(fun())
task
协程对象不能直接运行,在注册事件循环的时候,其实是run_until_complete方法将协程包装成为了一个任务(task)对象。所谓task对象是Future类的子类。保存了协程运行后的状态,用于未来获取协程的结果。
import asyncio
async def fun():
print('hello word')
return 'miao'
loop = asyncio.get_event_loop()
task = loop.create_task(fun())
print(task)
loop.run_until_complete(task)
print(task)
创建task后,task在加入事件循环之前是pending状态,因为do_some_work中没有耗时的阻塞操作,task很快就执行完毕了。后面打印的finished状态。
asyncio.ensure_future 和 loop.create_task都可以创建一个task,
run_until_complete的参数是一个futrue对象。当传入一个协程,其内部会自动封装成task,task是Future的子类。isinstance(task, asyncio.Future)将会输出True。
绑定回调
在task执行完毕的时候可以获取执行的结果,回调的最后一个参数是future对象,通过该对象可以获取协程返回值。如果回调需要多个参数,可以通过偏函数导入。
import asyncio
async def fun():
print('hello word')
return 'miao'
def callback(future):
print('Callback: ', future.result())
loop = asyncio.get_event_loop()
task = loop.create_task(fun())
#print(task)
task.add_done_callback(callback)
loop.run_until_complete(task)
#print(task)
也可以使用ensure_future获取返回值
import asyncio
async def fun():
print('hello word')
return 'miao'
#def callback(future):
#print('Callback: ', future.result())
loop = asyncio.get_event_loop()
#task = loop.create_task(fun())
#task.add_done_callback(callback)
task = asyncio.ensure_future(fun())
loop.run_until_complete(task)
print('the fun() return is: {}'.format(task.result()))
await阻塞
使用async可以定义协程对象,使用await可以针对耗时的操作进行挂起,就像生成器里的yield一样,函数让出控制权。协程遇到await,事件循环将会挂起该协程,执行别的协程,直到其他的协程也挂起或者执行完毕,再进行下一个协程的执行。耗时的操作一般是一些IO操作,例如网络请求,文件读取等。我们使用asyncio.sleep函数来模拟IO操作。协程的目的也是让这些IO操作异步化。
#coding:utf-8
import asyncio
import threading
import time
async def hello():
print("hello 1")
r = await asyncio.sleep(1)
print("hello 2")
def main():
loop = asyncio.get_event_loop()
print("begin")
loop.run_until_complete(hello())
loop.close()
print("end")
if __name__ == "__main__":
main()
create_task 和 create_server
create_server 创建服务 web服务
create_task 创建任务