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 PesterMessage(object): def __init__(self, recipient, count, king): self.recipient = recipient self.count = count self.king = king 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, queue, name): Actor.__init__(self) self._queue = queue self.name = name self.message_map = { CountMessage: self.handle_count, PesterMessage: self.pester_king} def handle_count(self, source, message): print "<%s> Oh fine then." % self.name for count in range(message.count): time.sleep(1) print "<%s> %s" % (self.name, count) def pester_king(self, source, message): print "<%s> I'll go pester the other king." % (self.name) message.king.__receive__( self, CountMessage(message.king, message.count)) print "<%s> done pestering." % self.name count_queue = Queue.Queue() king1 = KingCounter(count_queue, king1) king2 = KingCounter(count_queue, king2) 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(king1, counting)) count_queue.put(PesterMessage(king2, 1, king1)) count_queue.join()