33
44
55async 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)
810 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+
1213 # put the item in the queue
1314 await queue .put (item )
1415
@@ -20,19 +21,23 @@ async def consume(queue):
2021 while True :
2122 # wait for an item from the producer
2223 item = await queue .get ()
24+
25+ # the producer emits None to indicate that it is done
2326 if item is None :
24- # the producer emits None to indicate that it is done
2527 break
2628
27- # process the item
29+ # process the item (simulate i/o operation using sleep)
2830 print ('consuming item {}...' .format (item ))
29- # simulate i/o operation using sleep
3031 await asyncio .sleep (random .random ())
3132
3233
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+
3341loop = 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 ())
3843loop .close ()
0 commit comments