3
3
4
4
5
5
async def produce (queue , n ):
6
- for x in range (1 , n + 1 ):
7
- # produce an item
6
+ # produce n items
7
+ for x in range (1 , n + 1 ):
8
+
9
+ # produce an item (simulate i/o operation using sleep)
8
10
print ('producing {}/{}' .format (x , n ))
9
- # simulate i/o operation using sleep
10
- await asyncio .sleep (random .random ())
11
- item = str (x )
11
+ item = await asyncio .sleep (random .random (), result = x )
12
+
12
13
# put the item in the queue
13
14
await queue .put (item )
14
15
@@ -20,19 +21,23 @@ async def consume(queue):
20
21
while True :
21
22
# wait for an item from the producer
22
23
item = await queue .get ()
24
+
25
+ # the producer emits None to indicate that it is done
23
26
if item is None :
24
- # the producer emits None to indicate that it is done
25
27
break
26
28
27
- # process the item
29
+ # process the item (simulate i/o operation using sleep)
28
30
print ('consuming item {}...' .format (item ))
29
- # simulate i/o operation using sleep
30
31
await asyncio .sleep (random .random ())
31
32
32
33
34
+ async def main ():
35
+ queue = asyncio .Queue ()
36
+ producer_coro = produce (queue , 10 )
37
+ consumer_coro = consume (queue )
38
+ await asyncio .gather (producer_coro , consumer_coro )
39
+
40
+
33
41
loop = asyncio .get_event_loop ()
34
- queue = asyncio .Queue ()
35
- producer_coro = produce (queue , 10 )
36
- consumer_coro = consume (queue )
37
- loop .run_until_complete (asyncio .gather (producer_coro , consumer_coro ))
42
+ loop .run_until_complete (main ())
38
43
loop .close ()
0 commit comments