Skip to content

Instantly share code, notes, and snippets.

@rayshih
Last active May 17, 2017 03:17
Show Gist options
  • Select an option

  • Save rayshih/4144d6b8bc045fc26daf8887bd0cb4e2 to your computer and use it in GitHub Desktop.

Select an option

Save rayshih/4144d6b8bc045fc26daf8887bd0cb4e2 to your computer and use it in GitHub Desktop.
如何實作 async 的 generator

但只用純 Python 的 generator 沒辦法為 Python 的所有功能實作 async variant,因為這會有雞生蛋生雞問題。最簡單的矛盾:如果你只用 generator 實作 async API,那要怎麼實作 async 的 generator?

嗯?為什麼不行?

import asyncio
import time

def async_generator():
    @asyncio.coroutine
    def count_down(i, c):
        print('log from {}th async function with countdown {} and timestamp {}'.format(i, c, time.time()))
        if c == 0: return
        yield from asyncio.sleep(0.5)
        yield from count_down(i, c - 1)

    i = 1
    while i <= 5:
        yield count_down(i, i)
        i += 1

@asyncio.coroutine
def run_all(asyncGen):
    for a in asyncGen:
        yield from a

loop = asyncio.get_event_loop()
loop.run_until_complete(run_all(async_generator()))
loop.close()

output:

log from 1th async function with countdown 1 and timestamp 1494816543.0441651
log from 1th async function with countdown 0 and timestamp 1494816543.549279
log from 2th async function with countdown 2 and timestamp 1494816543.549315
log from 2th async function with countdown 1 and timestamp 1494816544.054571
log from 2th async function with countdown 0 and timestamp 1494816544.5569139
log from 3th async function with countdown 3 and timestamp 1494816544.5569532
log from 3th async function with countdown 2 and timestamp 1494816545.060334
log from 3th async function with countdown 1 and timestamp 1494816545.564309
log from 3th async function with countdown 0 and timestamp 1494816546.0687401
log from 4th async function with countdown 4 and timestamp 1494816546.0687969
log from 4th async function with countdown 3 and timestamp 1494816546.573986
log from 4th async function with countdown 2 and timestamp 1494816547.075812
log from 4th async function with countdown 1 and timestamp 1494816547.581194
log from 4th async function with countdown 0 and timestamp 1494816548.086391
log from 5th async function with countdown 5 and timestamp 1494816548.086432
log from 5th async function with countdown 4 and timestamp 1494816548.5881221
log from 5th async function with countdown 3 and timestamp 1494816549.08834
log from 5th async function with countdown 2 and timestamp 1494816549.5930529
log from 5th async function with countdown 1 and timestamp 1494816550.0984662
log from 5th async function with countdown 0 and timestamp 1494816550.603544

refs:

https://gist.github.com/rayshih/e7d736e19d172d1e1ebb127ffc26fe2b

@rayshih
Copy link
Copy Markdown
Author

rayshih commented May 15, 2017

根本裝 python3 的時間都比寫這個長

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment