Skip to content

Instantly share code, notes, and snippets.

@aidiary
Last active November 1, 2021 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aidiary/1922b22a580c416179d779d3560695e1 to your computer and use it in GitHub Desktop.
Save aidiary/1922b22a580c416179d779d3560695e1 to your computer and use it in GitHub Desktop.
asyncioのサンプルプログラム
import asyncio
async def main():
print('tim')
# タスクを作成
task = asyncio.create_task(foo('text'))
# 別のタスクに処理を譲る => fooが動き出す
await asyncio.sleep(0.5)
print('finished')
async def foo(text):
print(text)
# 別のタスクに処理を譲る => mainが続きから動き出す
await asyncio.sleep(1)
asyncio.run(main())
import asyncio
async def fetch_data():
print('start fetching')
# データの取得を待っている間(sleepで模擬)に他のタスク(task2)を起動
await asyncio.sleep(2)
print('done fetching')
return {'data': 1}
async def print_numbers():
for i in range(10):
print(i)
# 他のタスクが実行可能なら起動
await asyncio.sleep(0.5)
async def main():
task1 = asyncio.create_task(fetch_data())
task2 = asyncio.create_task(print_numbers())
# task1が終わるまで待つ(他のタスクに処理は譲る)
# task1が終わったら戻り値をvalueに格納する
value = await task1
print('***', value)
await task2
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment