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