fork download
  1. import asyncio
  2. import time
  3.  
  4.  
  5. async def cook_sushi():
  6. """sushiを握るのには3秒または7秒かかる"""
  7. print('sushi職人「sushi一丁!」')
  8. await asyncio.sleep(sushi_cook_time)
  9. print('sushi職人「sushiお待ち!」')
  10. return "sushi"
  11.  
  12.  
  13. async def cook_miso():
  14. """misoは1秒でできる"""
  15. print('sushi職人「miso一丁!」')
  16. await asyncio.sleep(1)
  17. print('sushi職人「misoお待ち!」')
  18. return "miso"
  19.  
  20.  
  21. def eat(dish):
  22. print(f"客「{dish}うまあ😋」")
  23.  
  24.  
  25. async def case1():
  26. """Case1: 寿司も味噌汁も頼んでおとなしく待ち、来た順に食う"""
  27. for future in asyncio.as_completed([cook_sushi(), cook_miso()]):
  28. result = await future
  29. eat(result)
  30.  
  31. return None
  32.  
  33.  
  34. async def case2():
  35. """Case2: 寿司を頼んでから5秒かかっても来なかったら店を出る"""
  36. try:
  37. result = await asyncio.wait_for(cook_sushi(), timeout=5.0)
  38. eat(result)
  39. except asyncio.TimeoutError:
  40. print('客「sushiが来ないなら帰らせて頂く」')
  41. return None
  42.  
  43.  
  44. async def case3():
  45. """Case3: 寿司を頼んでから5秒かかっても来なかったら味噌汁を頼む"""
  46. done, pending = await asyncio.wait(
  47. [cook_sushi(), asyncio.sleep(5)], return_when=asyncio.FIRST_COMPLETED)
  48. for d in done:
  49. result = d.result()
  50. if result == 'sushi':
  51. eat(result)
  52. else:
  53. # sushi が来なかった場合 (asyncio.sleep(5)の戻り値は None)
  54. result = await cook_miso()
  55. eat(result)
  56. if len(pending) > 0:
  57. done, pending = await asyncio.wait(
  58. pending, return_when=asyncio.ALL_COMPLETED)
  59. for d in done:
  60. eat(d.result())
  61.  
  62.  
  63. if __name__ == '__main__':
  64. #sushi_cook_time = 3
  65. sushi_cook_time = 7
  66.  
  67. loop = asyncio.get_event_loop()
  68. print(case1.__doc__)
  69. time.sleep(1)
  70. result = loop.run_until_complete(case1())
  71. print('')
  72. print(case2.__doc__)
  73. time.sleep(1)
  74. result = loop.run_until_complete(case2())
  75. print('')
  76. print(case3.__doc__)
  77. time.sleep(1)
  78. result = loop.run_until_complete(case3())
Time limit exceeded #stdin #stdout 5s 16280KB
stdin
Standard input is empty
stdout
Standard output is empty