Files

67 lines
2.1 KiB
Python

import asyncio
import logging
import random
# Logging konfigurieren, damit wir genau sehen, wer was tut (inkl. Stream & Datei)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("pasta.log", mode="w"),
logging.StreamHandler()
]
)
# Anzahl der Mahlzeiten begrenzen, damit das Programm regulär endet
MAX_MAHLZEITEN = 3
async def person(name: str, linke_gabel: asyncio.Lock, rechte_gabel: asyncio.Lock):
mahlzeiten = 0
while mahlzeiten < MAX_MAHLZEITEN:
logging.info(f"{name} hat Hunger und versucht, die linke Gabel zu bekommen.")
# Versuchen, die linke Gabel zu bekommen
async with linke_gabel:
logging.info(f"{name} hat die linke Gabel erhalten.")
# Kurze Wartezeit / Zwischenschritt (z.B. kurzes Nachdenken)
await asyncio.sleep(random.uniform(0.1, 0.3))
logging.info(f"{name} versucht, die rechte Gabel zu bekommen.")
# Versuchen, die rechte Gabel zu bekommen
async with rechte_gabel:
logging.info(f"{name} hat auch die rechte Gabel und isst jetzt (Mahlzeit {mahlzeiten + 1}).")
await asyncio.sleep(random.uniform(0.5, 1.0)) # Essen dauert
logging.info(f"{name} hat die rechte Gabel wieder weggelegt.")
logging.info(f"{name} hat die linke Gabel weggelegt und denkt nach.")
mahlzeiten += 1
# Warten zwischen zwei Versuchen, erneut Gabeln zu bekommen
await asyncio.sleep(random.uniform(0.5, 1.0))
logging.info(f"{name} ist satt und beendet das Essen.")
async def main():
# Gabeln als asyncio.Locks repräsentieren
gabel1 = asyncio.Lock()
gabel2 = asyncio.Lock()
gabel3 = asyncio.Lock()
# Drei Personen / Philosophen starten
await asyncio.gather(
person("Alice", gabel1, gabel2),
person("Bob", gabel2, gabel3),
person("Charlie", gabel3, gabel1)
)
logging.info("Alle Personen sind satt. Programm beendet.")
if __name__ == "__main__":
asyncio.run(main())