swactor/examples/python/hello_async.py
zacheryasc fc8e766bd3 feat: jupyter example (#10)
Add a Python getting-started Jupyter notebook and reorganize the Python examples under examples/python/.

- examples/python/getting_started.ipynb: add notebook demonstrating the single-threaded tick loop (`spawn`/`send`/`tick`/`inbox`/`try_recv`) and the multi-threaded path via `RuntimeConfig` + `rt.run()`/`handle.shutdown()`
- examples/: relocate `hello_async.py` and `hello_single_thread.py` under `examples/python/`
- pyproject.toml: add a `dev` dependency group containing jupyter and ipykernel
- uv.lock: regenerate the lockfile for the new dev dependencies (2452 lines)

Signed-off-by: Zachery Aaron Shores-Chmielewski <zacheryasc@gmail.com>
2026-02-06 14:04:48 +00:00

39 lines
914 B
Python

"""Async hello world: runtime runs in background threads, driven from asyncio."""
import asyncio
from swactor import Runtime, RuntimeConfig
async def recv(inbox, timeout=1.0):
"""Poll an inbox until a message arrives."""
while timeout > 0:
msg = inbox.try_recv()
if msg is not None:
return msg
await asyncio.sleep(0.01)
timeout -= 0.01
return None
async def main():
rt = Runtime(RuntimeConfig(num_threads=2))
def echo(ctx, msg):
ctx.send(msg["reply_to"], f"hello, {msg['name']}!")
addr = rt.spawn(echo)
inbox = rt.inbox()
handle = rt.run()
for name in ["alice", "bob", "charlie"]:
handle.send(addr, {"name": name, "reply_to": inbox.addr})
reply = await recv(inbox)
print(reply)
# show us our actors!
print(handle.stats())
handle.shutdown()
handle.join()
asyncio.run(main())