API basada en asyncio. Se conecta a un único servidor, adquiere una clave y la libera de inmediato.
broker = TicketBroker.connect("127.0.0.1:5225")
try:
await broker.wait_ready(5)
ticket = await broker.acquire("key", wait=5, lease=30)
await ticket.release()
print("pass")
finally:
broker.close()Ejemplo que verifica que, aunque varias tareas asyncio repitan depósitos/retiros excluyéndose mutuamente mediante un bloqueo por cuenta, el saldo siempre vuelve al valor inicial. Con async with ticket la liberación es automática al salir del bloque.
async def transaction(broker: TicketBroker, account: int, delta: int) -> None:
key = f"account-{account}"
try:
ticket = await broker.acquire(key, WAIT, LEASE)
except Exception as e:
log.error("account %s acquire failed: %s", account, e)
return
async with ticket:
before = BALANCES[account]
await asyncio.sleep(0)
after = before + delta
BALANCES[account] = after
action, sign = ("withdraw", "-") if delta < 0 else ("deposit", "+")
log.info("account %s %s %s$%s -> $%s", account, action, sign, AMOUNT, after)Consulta el ejemplo completo en test_example.py, test_bank.py, test_bench.py.