import asyncio


class StockActor:
    def __init__(self, stock):
        self.stock = stock
        self.mailbox = asyncio.Queue(maxsize=10)

    async def run(self):
        while True:
            message = await self.mailbox.get()
            if message is None:
                return
            quantity, reply = message
            accepted = 0 < quantity <= self.stock
            if accepted:
                self.stock -= quantity
            reply.set_result(accepted)


async def main():
    actor = StockActor(1)
    worker = asyncio.create_task(actor.run())
    replies = [asyncio.get_running_loop().create_future()
               for _ in range(2)]
    for reply in replies:
        await actor.mailbox.put((1, reply))
    result = await asyncio.gather(*replies)
    await actor.mailbox.put(None)
    await worker
    assert result == [True, False]
    assert actor.stock == 0
    print("两条消息顺序处理，库存没有超卖")


asyncio.run(main())
