python3 异步模块asyncio

yield方法引入,

这里存在的问题是,如果你想创建从0到1,000,000这样一个很大的序列,你不得不创建能容纳1,000,000个整数的列表。

但是当加入了生成器之后,你可以不用创建完整的序列,你只需要能够每次保存一个整数的内存即可。

import asyncio

@asyncio.coroutine
def countdown(number, n):
    while n > 0:
        yield from asyncio.sleep(1)
        print("T-minus", n, "({})".format(number))
        n -= 1
        if n == 10 and number=="A":
            raise ValueError

loop = asyncio.get_event_loop()

tasks = [
    asyncio.ensure_future(countdown("A", 20)),
    asyncio.ensure_future(countdown("B", 33)),
]
loop.run_until_complete(asyncio.wait(tasks))

loop.close()

看代码

import asyncio

@asyncio.coroutine
def countdown(number, n):
    while n > 0:
        yield from asyncio.sleep(1)
        print("T-minus", n, "({})".format(number))
        n -= 1
        if n == 10 and number=="A":
            raise ValueError

loop = asyncio.get_event_loop()

tasks = [
    asyncio.ensure_future(countdown("A", 20)),
    asyncio.ensure_future(countdown("B", 33)),
]
loop.run_until_complete(asyncio.wait(tasks))

loop.close()

原理讲的特别好

http://python.jobbole.com/86481/

猜你喜欢

转载自www.cnblogs.com/renfanzi/p/9212410.html
今日推荐