ごはんでまなぶ非同期処理

_images/gohan.png
  • 「米を炊く」と「調理する」は同時にできる

  • 「味噌汁をつくる」が終わってから「おかずをつくる」

  • 「米を炊く」と「調理する」が両方おわったら「いただきます」

コード例

 1import asyncio
 2import time
 3import logging
 4
 5logging.basicConfig(level=logging.INFO, format="%(asctime)s %(message)s", datefmt="%X")
 6
 7
 8async def kome():
 9    logging.info("米を炊くヨ")
10    await asyncio.sleep(10)
11    logging.info("米が炊けたヨ")
12
13
14async def chori():
15    logging.info("調理するヨ")
16
17    logging.info("味噌汁つくるヨ")
18    await asyncio.sleep(3)
19    logging.info("味噌汁できたヨ")
20
21    logging.info("おかずつくるヨ")
22    await asyncio.sleep(6)
23    logging.info("おかずできたヨ")
24
25    logging.info("調理おわったよヨ")
26
27
28def taberu():
29    logging.info("いただきます")
30    time.sleep(3)
31    logging.info("ごちそうさまでした")
32
33
34async def itadakimasu():
35
36    logging.info("--- ご飯できるまで待つ ---")
37
38    kome_task = asyncio.create_task(kome())
39    chori_task = asyncio.create_task(chori())
40    await kome_task
41    await chori_task
42
43    logging.info("--- ご飯できたので食べる ---")
44
45    taberu()
46
47
48asyncio.run(itadakimasu())

出力例

14:47:14 --- ご飯できるまで待つ ---
14:47:14 米を炊くヨ
14:47:14 調理するヨ
14:47:14 味噌汁つくるヨ
14:47:17 味噌汁できたヨ
14:47:17 おかずつくるヨ
14:47:23 おかずできたヨ
14:47:23 調理おわったよヨ
14:47:24 米が炊けたヨ
14:47:24 --- ご飯できたので食べる ---
14:47:24 いただきます
14:47:27 ごちそうさまでした