参考:https://www.liaoxuefeng.com/wiki/1016959663602400/1017970488768640
以下所有内容都是个人理解:
1、几个名词
asyn:异步 await:等待
2、协程
协程,跟线程一样,有一些库能够方便的支持我们使用,,能够遇到耗时的操作的时候,自动帮我们切换到别的协程当中去
3、举例子1
同一个线程号,因此,相当于一段程序
import threading
import asyncio
@asyncio.coroutine
def hello():
print('Hello world! (%s)' % threading.currentThread())
yield from asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
运行结果:
Hello world! (<_MainThread(MainThread, started 18860)>)
Hello world! (<_MainThread(MainThread, started 18860)>)
Hello again! (<_MainThread(MainThread, started 18860)>)
Hello again! (<_MainThread(MainThread, started 18860)>)
4、举例子2async/await
只替换了两个地方:
- 把
@asyncio.coroutine
替换为async
; - 把
yield from
替换为await
。
import threading
import asyncio
# @asyncio.coroutine
# def hello():
# print('Hello world! (%s)' % threading.currentThread())
# yield from asyncio.sleep(1)
# print('Hello again! (%s)' % threading.currentThread())
async def hello():
print("Hello world!")
r = await asyncio.sleep(1)
print("Hello again!")
loop = asyncio.get_event_loop()
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
运行结果
Hello world!
Hello world!
Hello again!
Hello again!
5、关于后半部分的说明
建立一个程序:
loop = asyncio.get_event_loop()
添加需要切换的执行的协程g:
tasks = [hello(), hello()]
开始运行这些协程
loop.run_until_complete(asyncio.wait(tasks))
回收资源:
loop.close()