Add an actor "state mutation" via messages example

actor_state_via_messages
Tyler Goodlet 2021-01-24 14:54:46 -05:00
parent ce61230815
commit 7f8c5cdfe6
1 changed files with 51 additions and 0 deletions

View File

@ -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)