2021-01-24 19:54:46 +00:00
|
|
|
from itertools import cycle
|
|
|
|
from pprint import pformat
|
2021-01-24 20:18:52 +00:00
|
|
|
from dataclasses import dataclass, field
|
2021-01-24 19:54:46 +00:00
|
|
|
|
|
|
|
import trio
|
|
|
|
import tractor
|
|
|
|
|
2021-01-24 20:18:52 +00:00
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class MyProcessStateThing:
|
|
|
|
state: dict = field(default_factory=dict)
|
|
|
|
|
|
|
|
def update(self, msg: dict):
|
|
|
|
self.state.update(msg)
|
|
|
|
|
|
|
|
|
|
|
|
_actor_state = MyProcessStateThing()
|
2021-01-24 19:54:46 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def update_local_state(msg: dict):
|
2021-01-24 20:18:52 +00:00
|
|
|
"""Update process-local state from sent message and exit.
|
2021-01-24 19:54:46 +00:00
|
|
|
|
2021-01-24 20:18:52 +00:00
|
|
|
"""
|
2021-01-24 19:54:46 +00:00
|
|
|
actor = tractor.current_actor()
|
|
|
|
|
2021-01-24 20:18:52 +00:00
|
|
|
global _actor_state
|
|
|
|
|
|
|
|
|
2021-01-24 19:54:46 +00:00
|
|
|
print(f'Yo we got a message {msg}')
|
|
|
|
|
|
|
|
# update the "actor state"
|
|
|
|
_actor_state.update(msg)
|
|
|
|
|
2021-01-24 20:18:52 +00:00
|
|
|
print(f'New local "state" for {actor.uid} is {pformat(_actor_state.state)}')
|
2021-01-24 19:54:46 +00:00
|
|
|
|
|
|
|
# we're done so exit this task running in the subactor
|
|
|
|
|
|
|
|
|
|
|
|
async def main():
|
|
|
|
# Main process/thread that spawns one sub-actor and sends messages
|
|
|
|
# to it to update it's state.
|
|
|
|
|
|
|
|
actor_portals = []
|
|
|
|
|
|
|
|
# XXX: that subactor can **not** outlive it's parent, this is SC.
|
|
|
|
async with tractor.open_nursery() as tn:
|
|
|
|
|
|
|
|
portal = await tn.start_actor('even_boy', enable_modules=[__name__])
|
|
|
|
actor_portals.append(portal)
|
|
|
|
|
|
|
|
portal = await tn.start_actor('odd_boy', enable_modules=[__name__])
|
|
|
|
actor_portals.append(portal)
|
|
|
|
|
|
|
|
for i, (count, portal) in enumerate(
|
|
|
|
zip(range(100), cycle(actor_portals))
|
|
|
|
):
|
|
|
|
await portal.run(update_local_state, msg={f'msg_{i}': count})
|
|
|
|
|
2021-01-24 20:18:52 +00:00
|
|
|
# blocks here indefinitely synce we spawned "daemon actors" using
|
2021-01-24 19:54:46 +00:00
|
|
|
# .start_actor()`, you'll need to control-c to cancel.
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
trio.run(main)
|