Poc me a python pub/sub snippet
- User
Poc me a python pub/sub snippet
Assistant
Here's a simple Python pub/sub implementation:
import threading import queue import time class PubSub: def __init__(self): self.subscribers = {} self.lock = threading.Lock() def subscribe(self, topic, callback): with self.lock: if topic not in self.subscribers: self.subscribers[topic] = [] self.subscribers[topic].append(callback) def unsubscribe(self, topic, callback): with self.lock: if topic in self.subscribers and callback in self.subscribers[topic]: self.subscribers[topic].remove(callback) def publish(self, topic, message): with self.lock: if topic in self.subscribers: for callback in self.subscribers[topic]: callback(message) # Example usage def listener1(message): print(f"Listener 1 received: {message}") def listener2(message): print(f"Listener 2 received: {message}") if __name__ == "__main__": pubsub = PubSub() # Subscribe to topics pubsub.subscribe("weather", listener1) pubsub.subscribe("weather", listener2) pubsub.subscribe("sports", listener1) # Publish messages pubsub.publish("weather", "It's sunny today!") pubsub.publish("sports", "Team won the championship!") # Unsubscribe and publish again pubsub.unsubscribe("weather", listener2) pubsub.publish("weather", "It's going to rain tomorrow")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.