Mercurial
comparison grok_interview/test.py @ 51:68fa88ac73fe
Interview prep for xAI
| author | June Park <parkjune1995@gmail.com> |
|---|---|
| date | Mon, 15 Dec 2025 19:55:17 -0800 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 46:b9a40c633c93 | 51:68fa88ac73fe |
|---|---|
| 1 import asyncio | |
| 2 import random | |
| 3 | |
| 4 | |
| 5 class database: | |
| 6 def __init__(self): | |
| 7 self.values = 0 | |
| 8 self._lock = asyncio.Lock() | |
| 9 | |
| 10 def get(self): | |
| 11 return self.values | |
| 12 | |
| 13 def set(self, values): | |
| 14 self.values = values | |
| 15 | |
| 16 | |
| 17 async def add(number, db: database, random_wait: int): | |
| 18 async with db._lock: | |
| 19 current = db.get() | |
| 20 await asyncio.sleep(random.random() * 0.05) | |
| 21 db.set(current + number) | |
| 22 | |
| 23 | |
| 24 async def main(): | |
| 25 db = database() | |
| 26 tasks = [] | |
| 27 for i in range(100): | |
| 28 tasks.append(asyncio.create_task( | |
| 29 add(i, db, random.randint(1, 5)) | |
| 30 )) | |
| 31 await asyncio.gather(*tasks) | |
| 32 print(db.get()) | |
| 33 print(sum([i for i in range(100)])) | |
| 34 | |
| 35 asyncio.run(main()) | |
| 36 |