view grok_interview/test.py @ 56:92b097d70af4

Updated so that fzf works out of the box.
author June Park <me@mrjunejune.com>
date Tue, 16 Dec 2025 21:01:45 -0500
parents 68fa88ac73fe
children
line wrap: on
line source

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())