Concurrency
Xyra provides utilities to handle concurrent operations efficiently, allowing you to run blocking code without blocking the event loop.
Running Blocking Code
Use the to_thread decorator to run synchronous functions in a separate thread, preventing them from blocking the async event loop.
Python
from xyra import App
from xyra.concurrency import to_thread
import time
app = App()
@to_thread
def blocking_task(duration: int):
"""A blocking function that simulates I/O or CPU intensive work."""
time.sleep(duration)
return f"Task completed after {duration} seconds"
@app.get("/async")
async def async_endpoint():
# This won't block the event loop
result = await blocking_task(2)
return {"result": result}
The @to_thread decorator automatically runs the decorated function in a thread pool, allowing your async handlers to remain non-blocking.