Ping-Pong¶
The simplest actor communication example.
Code¶
import asyncio
from pulsing.actor import Actor, SystemConfig, create_actor_system
class PingPong(Actor):
async def receive(self, msg):
if msg == "ping":
return "pong"
return f"echo: {msg}"
async def main():
system = await create_actor_system(SystemConfig.standalone())
actor = await system.spawn("pingpong", PingPong())
print(await actor.ask("ping")) # -> pong
print(await actor.ask("hello")) # -> echo: hello
await system.shutdown()
asyncio.run(main())
Run¶
Key Points¶
Actoris the base class - implementreceive()to handle messages- Any Python object can be a message (string, dict, list, etc.)
actor.ask(msg)sends a message and waits for responsesystem.shutdown()cleanly stops all actors