Reserving a Slot Before You Await
In this lesson, you port an asyncio reservation for a station poll and make it safe. Ridge’s satellite uplink has one extra polling slot this shift, and two callers ask for it at the same moment: the dashboard’s auto-refresh and the operator’s Refresh button. Can both of them get it?
In the Python script, stock counts the slots left: one. poll() stands in for the station poll, and
the cache answers it at once. reserve() returns "sold out" when the stock is zero. Otherwise, it
awaits the poll, takes one off the stock, and returns "reserved":
import asyncio
stock = 1
async def poll(): ... # the cache answers at once
async def reserve():
global stock
if stock == 0:
return "sold out"
await poll()
stock -= 1
return "reserved"
async def main():
results = await asyncio.gather(reserve(), reserve())
print(results, stock)
asyncio.run(main())
asyncio.gather() runs two reserve() calls together, and the script prints
['reserved', 'sold out'] 0.
In the JavaScript port, stock is a let, a variable you can reassign. There’s no global line:
assigning to stock inside a function updates the outer let. poll() is an async function with an
empty body, so its promise is fulfilled at once.