import Queue import threading import time class XuddMaster(object): pass class CountMessage(object): def __init__(self, recipient, count): self.recipient = recipient self.count = count class Actor(object): def __init__(self): self.lock = threading.Lock() def __receive__(self, source, message): self.lock.acquire() message_handler = self.message_map.get(message.__class__) if message_handler: message_handler(source, message) self.lock.release() class TaskDispatcher(threading.Thread): def __init__(self, queue, name): threading.Thread.__init__(self) self.queue = queue self.name = name def run(self): while True: message = self.queue.get() message.recipient.__receive__(None, message) print self.name self.queue.task_done() class KingCounter(Actor): def __init__(self): Actor.__init__(self) self.message_map = { CountMessage: self.handle_count} def handle_count(self, source, message): print "Oh fine then." for count in range(message.count): time.sleep(1) print count king = KingCounter() count_queue = Queue.Queue() for i in range(3): t = TaskDispatcher(count_queue, 'd%s' % i) t.setDaemon(True) t.start() for counting in [5, 2, 3, 10, 2, 8]: count_queue.put(CountMessage(king, counting)) count_queue.join()