Skip to content

Instantly share code, notes, and snippets.

@EgorBron
Last active November 17, 2022 16:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EgorBron/84302d00f8dcae19cffa7ba14fddbe8d to your computer and use it in GitHub Desktop.
Save EgorBron/84302d00f8dcae19cffa7ba14fddbe8d to your computer and use it in GitHub Desktop.
Асинхронность в Pyhton на примере готовки завтрака
import asyncio, time
from typing import List
class Toast:
is_fried = False
with_butter = False
with_jam = False
def start_fry(self):
print("Начинаем готовить тост.")
def end_fry(self):
print("Тост готов.")
self.is_fried = True
def apply_jam(self):
print("Мажем джем")
self.with_jam = True
def apply_butter(self):
print("Мажем масло")
self.with_butter = True
def __str__(self) -> str:
toast = "toast"
toast = ("fried " if self.is_fried else "") + toast
# уродливо
if self.with_jam or self.with_butter:
toast += " with "
if self.with_butter:
toast += "butter"
if self.with_jam and self.with_butter:
toast += " and jam"
elif self.with_jam:
toast += "jam"
return toast
async def pour_coffee():
print("Готовим кофе.")
await asyncio.sleep(5)
print("Кофе готов.")
return "coffee"
async def fry_eggs(count: int):
print("Греем сковородку...")
print(f"Готовятся яйца: {count}")
print("Готовим...")
await asyncio.sleep(30)
print("Яичница пожарена.")
return f"eggs x{count}"
async def fry_bacon(count: int):
print(f"Положили кусочков бекона на сковородку: {count}")
print("Жарим одну сторону бекона...")
await asyncio.sleep(20)
for i in range(count):
print(f"Переворачиваем кусочек: {i+1}")
print("Жарим другую сторону бекона...")
await asyncio.sleep(15)
print("Бекон готов.")
return f"bacon x{count}"
async def toast_bread(toasts: List[Toast]):
for toast in toasts:
toast.start_fry()
await asyncio.sleep(20)
for toast in toasts:
toast.end_fry()
toast.apply_butter()
toast.apply_jam()
return ", ".join(str(t) for t in toasts)
async def main():
start = time.time()
breakfast = "Наш завтрак из {ingredients} готов"
ingredients = []
ingredients.append(pour_coffee())
ingredients.append(fry_eggs(2))
ingredients.append(fry_bacon(3))
ingredients.append(toast_bread([Toast(), Toast()]))
result = await asyncio.gather(*ingredients) # в python 3.11 использовать asyncio.TagGroup
print(breakfast.format(ingredients=result))
print(f"Готовка завершена за {time.time()-start}")
asyncio.run(main())
import time
from typing import List
class Toast:
is_fried = False
with_butter = False
with_jam = False
def start_fry(self):
print("Начинаем готовить тост.")
def end_fry(self):
print("Тост готов.")
self.is_fried = True
def apply_jam(self):
print("Мажем джем")
self.with_jam = True
def apply_butter(self):
print("Мажем масло")
self.with_butter = True
def __str__(self) -> str:
toast = "toast"
toast = ("fried " if self.is_fried else "") + toast
# уродливо
if self.with_jam or self.with_butter:
toast += " with "
if self.with_butter:
toast += "butter"
if self.with_jam and self.with_butter:
toast += " and jam"
elif self.with_jam:
toast += "jam"
return toast
def pour_coffee():
print("Готовим кофе.")
time.sleep(5)
print("Кофе готов.")
return "coffee"
def fry_eggs(count: int):
print("Греем сковородку...")
print(f"Готовятся яйца: {count}")
print("Готовим...")
time.sleep(30)
print("Яичница пожарена.")
return f"eggs x{count}"
def fry_bacon(count: int):
print(f"Положили кусочков бекона на сковородку: {count}")
print("Жарим одну сторону бекона...")
time.sleep(20)
for i in range(count):
print(f"Переворачиваем кусочек: {i+1}")
print("Жарим другую сторону бекона...")
time.sleep(15)
print("Бекон готов.")
return f"bacon x{count}"
def toast_bread(toasts: List[Toast]):
for toast in toasts:
toast.start_fry()
time.sleep(20)
for toast in toasts:
toast.end_fry()
toast.apply_butter()
toast.apply_jam()
return ", ".join(str(t) for t in toasts)
start = time.time()
breakfast = "Наш завтрак из {ingredients} готов"
ingredients = []
ingredients.append(pour_coffee())
ingredients.append(fry_eggs(2))
ingredients.append(fry_bacon(3))
ingredients.append(toast_bread([Toast(), Toast()]))
print(breakfast.format(ingredients=ingredients))
print(f"Готовка завершена за {time.time()-start}")
import threading, time
from typing import List
class Toast:
is_fried = False
with_butter = False
with_jam = False
def start_fry(self):
print("Начинаем готовить тост.")
def end_fry(self):
print("Тост готов.")
self.is_fried = True
def apply_jam(self):
print("Мажем джем")
self.with_jam = True
def apply_butter(self):
print("Мажем масло")
self.with_butter = True
def __str__(self) -> str:
toast = "toast"
toast = ("fried " if self.is_fried else "") + toast
# уродливо
if self.with_jam or self.with_butter:
toast += " with "
if self.with_butter:
toast += "butter"
if self.with_jam and self.with_butter:
toast += " and jam"
elif self.with_jam:
toast += "jam"
return toast
def pour_coffee():
print("Готовим кофе.")
time.sleep(5)
print("Кофе готов.")
return "coffee"
def fry_eggs(count: int):
print("Греем сковородку...")
print(f"Готовятся яйца: {count}")
print("Готовим...")
time.sleep(30)
print("Яичница пожарена.")
return f"eggs x{count}"
def fry_bacon(count: int):
print(f"Положили кусочков бекона на сковородку: {count}")
print("Жарим одну сторону бекона...")
time.sleep(20)
for i in range(count):
print(f"Переворачиваем кусочек: {i+1}")
print("Жарим другую сторону бекона...")
time.sleep(15)
print("Бекон готов.")
return f"bacon x{count}"
def toast_bread(toasts: List[Toast]):
for toast in toasts:
toast.start_fry()
time.sleep(20)
for toast in toasts:
toast.end_fry()
toast.apply_butter()
toast.apply_jam()
return ", ".join(str(t) for t in toasts)
start = time.time()
breakfast = "Наш завтрак из {ingredients} готов"
ingredients = []
ingredients.append(threading.Thread(target=pour_coffee).start())
ingredients.append(threading.Thread(target=fry_eggs, args=[2]).start())
ingredients.append(threading.Thread(target=fry_bacon, args=[3]).start())
ingredients.append(threading.Thread(target=toast_bread, args=[[Toast(), Toast()]]).start())
pending = 4
while pending != 0:
for t in threading.enumerate():
if not t.is_alive(): pending -= 1
print(breakfast.format(ingredients=ingredients))
print(f"Готовка завершена за {time.time()-start}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment