美文网首页
python asyncio并发编程(3)

python asyncio并发编程(3)

作者: TheRightPath1 | 来源:发表于2020-01-20 15:41 被阅读0次

1. loop.run_forever()与loop.run_until_complete()的区别

(1) loop.run_forever():当我们传入指定的事件循环以后这个方法不会停止,会一直进行事件循环
(2) loop.run_until_complete():当我们传入指定的事件循环以后这个方法会在执行完事件循环以后停止事件循环
通过观察源码可以看出以上原因是因为loop.run_until_complete()在执行完事件循环以后加入了一个回调函数,回调函数会执行fun._loop.stop()放停止事件循环

2. 取消future(task)

import asyncio


async def get_url(sleep_time):
    await asyncio.sleep(2)
    print('sleep {} 秒'.format(sleep_time))


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    task1 = get_url(1)
    task2 = get_url(2)
    task3 = get_url(3)
    tasks = [task1, task2, task3]
    try:
        loop.run_until_complete(asyncio.wait(tasks))
    except KeyboardInterrupt as e:
        # 调用asyncio.Task.all_tasks()方法获取所有的task
        task = asyncio.Task.all_tasks()
        for i in task:
            print('取消task')
            # 调用cancel取消任务
            print(i.cancel())
        # 任务取消以后需要将loop停止
        loop.stop()
        # loop停止以后必须重新运行run_forever(),否则会报错
        loop.run_forever()
    finally:
        # close()方法会清空任务队列和进程池等等
        loop.close()

运行结果(按下ctrl+c以后)

取消task
True
取消task
True
取消task
True
取消task
True

3.在协程当中嵌套协程

import asyncio


async def compute(x, y):
    await asyncio.sleep(1)
    return x + y


async def print_sum(x, y):
    result = await compute(x, y)
    print('{} + {} = {}'.format(x, y, result))


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(print_sum(1, 2))
    loop.stop()

相关文章

网友评论

      本文标题:python asyncio并发编程(3)

      本文链接:https://www.haomeiwen.com/subject/xqmjzctx.html