diff grok_interview/thread.py @ 60:d64a8c189a77

Merged
author June Park <me@mrjunejune.com>
date Sat, 20 Dec 2025 13:56:01 -0500
parents 68fa88ac73fe
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/grok_interview/thread.py	Sat Dec 20 13:56:01 2025 -0500
@@ -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]
+