yeomko22 / TIL

Today I learned
1 stars 0 forks source link

python coroutines #99

Open yeomko22 opened 2 years ago

yeomko22 commented 2 years ago

Reference

coroutine 개념

coroutine을 만드는 방법

async def read_data(db):
    pass

@types.coroutine
def process_data(db):
    data = yield from read_data(db)
    ...
yeomko22 commented 2 years ago
def asyncio

async def main():
    print('hello')
    await asyncio.sleep(1)
    print('world')

asyncio.run(main())
import asyncio
import time

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(1, 'hello')
    await say_after(2, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())
async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    print(f"started at {time.strftime('%X')}")

    # Wait until both tasks are completed (should take
    # around 2 seconds.)
    await task1
    await task2

    print(f"finished at {time.strftime('%X')}")
yeomko22 commented 2 years ago

Awaitable

async def nested(): return 42

async def main():

Nothing happens if we just call "nested()".

# A coroutine object is created but not awaited,
# so it *won't run at all*.
nested()

# Let's do it differently now and await it:
print(await nested())  # will print "42".

asyncio.run(main())

- generator based coroutine은 현재 deprecated 되었으며 3.10 버전에서부터는 삭제될 예정
- Task는 코루틴 스케쥴링을 concurrently하게 수행하고 싶을 때 사용한다.
~~~python
import asyncio

async def nested():
    return 42

async def main():
    # Schedule nested() to run soon concurrently
    # with "main()".
    task = asyncio.create_task(nested())

    # "task" can now be used to cancel "nested()", or
    # can simply be awaited to wait until it is complete:
    await task

asyncio.run(main())