Mercurial
diff 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 |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/async_multi_threads/test.py Thu Dec 25 20:07:46 2025 -0800 @@ -0,0 +1,36 @@ +import asyncio +import random + + +class database: + def __init__(self): + self.values = 0 + self._lock = asyncio.Lock() + + def get(self): + return self.values + + def set(self, values): + self.values = values + + +async def add(number, db: database, random_wait: int): + async with db._lock: + current = db.get() + await asyncio.sleep(random.random() * 0.05) + db.set(current + number) + + +async def main(): + db = database() + tasks = [] + for i in range(100): + tasks.append(asyncio.create_task( + add(i, db, random.randint(1, 5)) + )) + await asyncio.gather(*tasks) + print(db.get()) + print(sum([i for i in range(100)])) + +asyncio.run(main()) +