From 7f8c5cdfe6279f89997552c95a7c20021515f3f8 Mon Sep 17 00:00:00 2001 From: Tyler Goodlet Date: Sun, 24 Jan 2021 14:54:46 -0500 Subject: [PATCH] Add an actor "state mutation" via messages example --- examples/actors/mutate_remote_state.py | 51 ++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 examples/actors/mutate_remote_state.py diff --git a/examples/actors/mutate_remote_state.py b/examples/actors/mutate_remote_state.py new file mode 100644 index 0000000..1d6554c --- /dev/null +++ b/examples/actors/mutate_remote_state.py @@ -0,0 +1,51 @@ +from itertools import cycle +from pprint import pformat + +import trio +import tractor + +_snd_chan, _recv_chan = trio.open_memory_channel(100) +_actor_state = {'some_state_stuff': None} + + +async def update_local_state(msg: dict): + + global _actor_state + actor = tractor.current_actor() + + print(f'Yo we got a message {msg}') + + # update the "actor state" + _actor_state.update(msg) + + print(f'New local "state" for {actor.uid} is {pformat(_actor_state)}') + + # 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}) + + # blocks here indefinitely synce we spawned "daemon actors using + # .start_actor()`, you'll need to control-c to cancel. + + +if __name__ == '__main__': + trio.run(main)