asyncio学习
概念
定义协程
async def MyCoroutine():
print("Hello, world")import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(MyCoroutine())创建task
两种方法创建task


绑定回调
阻塞和await
参考资料
Last updated
async def MyCoroutine():
print("Hello, world")import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(MyCoroutine())

Last updated
import asyncio
import time
now = lambda : time.time()
async def MyCoroutine(x):
print('Waiting', x)
start = now()
loop = asyncio.get_event_loop()
task = loop.create_task(MyCoroutine(2))
print(task)
loop.run_until_complete(task)
print(task)
print('TIME: ', now() - start)import time
import asyncio
now = lambda : time.time()
async def MyCoroutine(x):
print('Waiting: ', x)
return 'Done after {}s'.format(x)
def callback(future):
print('Callback: ', future.result())
start = now()
loop = asyncio.get_event_loop()
task = asyncio.ensure_future(MyCoroutine(3))
task.add_done_callback(callback)
loop.run_until_complete(task)
print('Task ret: ', task.result())
print('TIME: ', now() - start)import asyncio
import random
async def MyCoroutine(id):
process_time = random.randint(1, 5)
await asyncio.sleep(process_time)
print('协程:{}, 执行完毕。用时:{}秒'.format(id, process_time))
async def main():
tasks = [asyncio.ensure_future(MyCoroutine(i)) for i in range(100)]
await asyncio.gather(*tasks)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(main())
finally:
loop.close()