Mercurial
diff grok_interview/thread.py @ 51:68fa88ac73fe
Interview prep for xAI
| author | June Park <parkjune1995@gmail.com> |
|---|---|
| date | Mon, 15 Dec 2025 19:55:17 -0800 |
| parents | |
| children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/grok_interview/thread.py Mon Dec 15 19:55:17 2025 -0800 @@ -0,0 +1,32 @@ +# 1. data struture {} +# - multiple threads can access it +# - multiple threads can edit it if it is editable. (mutex) + + +from hashlib import sha256 +from threading import Lock + +class Subscribers: + def __init__(self): + self.id = sha256() + + def on_event(self, event): + pass + +class Publisher: + def __init__(self): + self._subscritions = {} + self.lock = Lock() + + def publish_event(self, event): + for subscriber_id, subscriber in enumerate(self._subscritions): + subscriber.on_event(event) + + def add_subscribers(self, subscriber: Subscribers): + with self.lock: + self._subscritions[subscriber.id] = subscriber + + def remove_subscribers(self, subscriber: Subscribers): + with self.lock: + del self._subscritions[subscriber.id] +