MCPcopy Create free account
hub / github.com/dabeaz/python-cookbook / Actor

Class Actor

src/12/defining_an_actor_task/actor.py:8–58  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6 pass
7
8class Actor:
9 def __init__(self):
10 self._mailbox = Queue()
11
12 def send(self, msg):
13 '''
14 Send a message to the actor
15 '''
16 self._mailbox.put(msg)
17
18 def recv(self):
19 '''
20 Receive an incoming message
21 '''
22 msg = self._mailbox.get()
23 if msg is ActorExit:
24 raise ActorExit()
25 return msg
26
27 def close(self):
28 '''
29 Close the actor, thus shutting it down
30 '''
31 self.send(ActorExit)
32
33 def start(self):
34 '''
35 Start concurrent execution
36 '''
37 self._terminated = Event()
38 t = Thread(target=self._bootstrap)
39 t.daemon = True
40 t.start()
41
42 def _bootstrap(self):
43 try:
44 self.run()
45 except ActorExit:
46 pass
47 finally:
48 self._terminated.set()
49
50 def join(self):
51 self._terminated.wait()
52
53 def run(self):
54 '''
55 Run method to be implemented by the user
56 '''
57 while True:
58 msg = self.recv()
59
60# Sample ActorTask
61class PrintActor(Actor):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected