|
| 1 | +# SPDX-FileCopyrightText: 2019 Damien P. George |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: MIT |
| 4 | +# |
| 5 | +# MicroPython uasyncio module |
| 6 | +# MIT license; Copyright (c) 2019 Damien P. George |
| 7 | +# |
| 8 | +# pylint: skip-file |
| 9 | + |
| 10 | +import asyncio |
| 11 | + |
| 12 | + |
| 13 | +def print_queue_info(queue: asyncio.Queue): |
| 14 | + print("Size:", queue.qsize()) |
| 15 | + print("Empty:", queue.empty()) |
| 16 | + print("Full:", queue.full()) |
| 17 | + |
| 18 | + |
| 19 | +async def put_queue(queue: asyncio.Queue, value): |
| 20 | + await queue.put(value) |
| 21 | + |
| 22 | + |
| 23 | +async def get_queue(queue: asyncio.Queue): |
| 24 | + print(await queue.get()) |
| 25 | + |
| 26 | + |
| 27 | +async def main(): |
| 28 | + # Can put and retrieve items in the right order |
| 29 | + print("=" * 10) |
| 30 | + queue = asyncio.Queue() |
| 31 | + await queue.put("a") |
| 32 | + await queue.put("b") |
| 33 | + |
| 34 | + print(await queue.get()) |
| 35 | + print(await queue.get()) |
| 36 | + |
| 37 | + # Waits for item to be put if get is called on empty queue |
| 38 | + print("=" * 10) |
| 39 | + queue = asyncio.Queue() |
| 40 | + |
| 41 | + task = asyncio.create_task(get_queue(queue)) |
| 42 | + await asyncio.sleep(0.01) |
| 43 | + print("putting on the queue") |
| 44 | + await queue.put("example") |
| 45 | + await task |
| 46 | + |
| 47 | + # Waits for item to be taken off the queue if max size is specified |
| 48 | + print("=" * 10) |
| 49 | + queue = asyncio.Queue(1) |
| 50 | + await queue.put("hello world") |
| 51 | + task = asyncio.create_task(put_queue(queue, "example")) |
| 52 | + await asyncio.sleep(0.01) |
| 53 | + print_queue_info(queue) |
| 54 | + print(await queue.get()) |
| 55 | + await task |
| 56 | + print_queue_info(queue) |
| 57 | + print(await queue.get()) |
| 58 | + |
| 59 | + # Raises an error if not waiting |
| 60 | + print("=" * 10) |
| 61 | + queue = asyncio.Queue(1) |
| 62 | + try: |
| 63 | + queue.get_nowait() |
| 64 | + except Exception as e: |
| 65 | + print(repr(e)) |
| 66 | + |
| 67 | + await queue.put("hello world") |
| 68 | + |
| 69 | + try: |
| 70 | + queue.put_nowait("example") |
| 71 | + except Exception as e: |
| 72 | + print(repr(e)) |
| 73 | + |
| 74 | + # Sets the size, empty, and full values as expected when no max size is set |
| 75 | + print("=" * 10) |
| 76 | + queue = asyncio.Queue() |
| 77 | + print_queue_info(queue) |
| 78 | + await queue.put("example") |
| 79 | + print_queue_info(queue) |
| 80 | + |
| 81 | + # Sets the size, empty, and full values as expected when max size is set |
| 82 | + print("=" * 10) |
| 83 | + queue = asyncio.Queue(1) |
| 84 | + print_queue_info(queue) |
| 85 | + await queue.put("example") |
| 86 | + print_queue_info(queue) |
| 87 | + |
| 88 | + |
| 89 | +asyncio.run(main()) |
0 commit comments