Книга: Learning Concurrency in Python
Назад: Locks
Дальше: Events and conditions

Queues

The asyncio.Queue implementation gives us another near identical implementation to that given to us in the standard queue module already present in Python.

In this example, we'll create both a producer and a consumer. The producer will produce articleIds between 1 and 5, while the consumer will try to read all of these articles. For both the producer and consumer, we'll define an appropriately named coroutine. Within our newsProducer coroutine, we'll perform the put command once every second that will put an ID onto our passed-in asyncio.Queue.

Within our newsConsumer function, we'll constantly try to perform a get request in order to retrieve an article ID from our shared queue. We'll then print out that we've consumed the said article ID and proceed to try and consume the next article:

import asyncio
import random
import time

@asyncio.coroutine
def newsProducer(myQueue):
while True:
yield from myQueue.put(random.randint(1,5))
yield from asyncio.sleep(1)

@asyncio.coroutine
def newsConsumer(myQueue):
while True:
articleId = yield from myQueue.get()
print("News Reader Consumed News Article {}", articleId)

myQueue = asyncio.Queue()

loop = asyncio.get_event_loop()

loop.create_task(newsProducer(myQueue))
loop.create_task(newsConsumer(myQueue))
try:
loop.run_forever()
finally:
loop.close()

When we execute the preceding program, you should see a constant stream of print statements coming from our newsConsumer coroutine. This demonstrates that we've successfully utilized our asyncio.Queue object for both our producer and consumer and have now achieved the communication that we desired:

$ python3.6 13_asyncioQueue.py
News Reader Consumed News Article {} 4
News Reader Consumed News Article {} 1
News Reader Consumed News Article {} 4
News Reader Consumed News Article {} 2
...
Назад: Locks
Дальше: Events and conditions