Mercurial
comparison async_multi_threads/test.py @ 69:551d9fc0a2ba
Updated wrong names.
| author | June Park <parkjune1995@gmail.com> |
|---|---|
| date | Thu, 25 Dec 2025 20:07:46 -0800 |
| parents | |
| children |
comparison
equal
deleted
inserted
replaced
| 68:70ca1d99f3fd | 69:551d9fc0a2ba |
|---|---|
| 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 |