Mercurial
comparison async_multi_threads/thread.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 # 1. data struture {} | |
| 2 # - multiple threads can access it | |
| 3 # - multiple threads can edit it if it is editable. (mutex) | |
| 4 | |
| 5 | |
| 6 from hashlib import sha256 | |
| 7 from threading import Lock | |
| 8 | |
| 9 class Subscribers: | |
| 10 def __init__(self): | |
| 11 self.id = sha256() | |
| 12 | |
| 13 def on_event(self, event): | |
| 14 pass | |
| 15 | |
| 16 class Publisher: | |
| 17 def __init__(self): | |
| 18 self._subscritions = {} | |
| 19 self.lock = Lock() | |
| 20 | |
| 21 def publish_event(self, event): | |
| 22 for subscriber_id, subscriber in enumerate(self._subscritions): | |
| 23 subscriber.on_event(event) | |
| 24 | |
| 25 def add_subscribers(self, subscriber: Subscribers): | |
| 26 with self.lock: | |
| 27 self._subscritions[subscriber.id] = subscriber | |
| 28 | |
| 29 def remove_subscribers(self, subscriber: Subscribers): | |
| 30 with self.lock: | |
| 31 del self._subscritions[subscriber.id] | |
| 32 |