Open yeomko22 opened 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')}")
import asyncio
async def nested(): return 42
async def main():
# 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())
Reference
coroutine 개념
coroutine을 만드는 방법