12.10 定义一个Actor任务
问题
解决方案
from queue import Queue
from threading import Thread, Event
class ActorExit(Exception): # Sentinel used for shutdown
pass
class Actor:
def __init__(self):
self._mailbox = Queue()
def send(self, msg):
self._mailbox.put(msg) # Send a message to the actor
def recv(self):
msg = self._mailbox.get() # Receive an incoming message
if msg is ActorExit:
raise ActorExit()
return msg
def close(self):
self.send(ActorExit) # Close the actor, thus shutting it down
def start(self):
self._terminated = Event() # Start concurrent execution
t = Thread(target=self._bootstrap)
t.daemon = True
t.start()
def _bootstrap(self):
try:
self.run()
except ActorExit:
pass
finally:
self._terminated.set()
def join(self):
self._terminated.wait()
def run(self):
while True: # Run method to be implemented by the user
msg = self.recv()
# Sample ActorTask
class PrintActor(Actor):
def run(self):
while True:
msg = self.recv()
print('Got:', msg)
p = PrintActor()
p.start()
p.send('Hello')
p.send('World')
p.close()
p.join()讨论
Last updated