并发和并行一直是容易混淆的概念。并发通常指有多个任务需要同时进行,并行则是同一时刻有多个任务执行。
asyncio实现并发,就需要多个协程来完成任务,每当有任务阻塞的时候就await,然后其他协程继续工作。创建多个协程的列表,然后将这些协程注册到时间循环中。
一、asyncio实现并发
import asyncio
import time
now = lambda:time.time()
def events_demo():
async def do_some_work(x):
print('Waiting:',x)
await asyncio.sleep(x)
return 'Done after {}s'.format(x)
start = now()
#创建多个协程对象
coroutine1=do_some_work(1)
coroutine1=do_some_work(2)
coroutine1=do_some_work(4)
#创建任务列表
tasks=[
asyncio.ensure_future(coroutine1),
asyncio.ensure_future(coroutine2),
asyncio.ensure_future(coroutine3)
]
#将任务列表注册到事件循环中
loop=asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
#获取返回的结果
for task in tasks:
print('Task ret:',task.result())
print('TIME:',now()-start)
二、实验总结
运行结果显示,并行的话应该为1+2+4=7秒;并发每个任务里面执行do_some_work,第一次耗时是1秒,遇到耗时执行其他协程,第二次耗时是2秒,遇到耗时执行其他协程,以此类推。遇到耗时进行阻塞进行其他协程,最长的耗时为4秒,三个任务4秒多执行完成。