Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/asyncio_examples/producer_consumer_task_done.py
1240 views
1
"""
2
A simple producer/consumer example using Queue.task_done and Queue.join
3
"""
4
5
import asyncio
6
import random
7
8
async def produce(queue, n):
9
for x in range(n):
10
# produce an item
11
print(('producing {}/{}'.format(x, n)))
12
# simulate i/o operation using sleep
13
await asyncio.sleep(random.random())
14
item = str(x)
15
# put the item in the queue
16
await queue.put(item)
17
18
19
async def consume(queue):
20
while True:
21
# wait for an item from the producer
22
item = await queue.get()
23
24
# process the item
25
print(("consuming {}...".format(item)))
26
# simulate i/o operation using sleep
27
await asyncio.sleep(random.random())
28
29
# notify the queue that the item has been processed.
30
queue.task_done()
31
32
async def run(n):
33
queue = asyncio.Queue()
34
# schedule a consumer
35
consumer = asyncio.ensure_future(consume(queue))
36
# run the producer and wait for completion
37
await produce(queue, n)
38
# wait until the consumer has processed all items
39
await queue.join()
40
# the consumer is still awaiting for an item, cancel it
41
consumer.cancel()
42
43
loop = asyncio.get_event_loop()
44
loop.run_until_complete(run(10))
45
loop.close()
46
47