Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/python/asyncio_examples/producer.py
1240 views
1
import asyncio
2
import random
3
4
async def produce(queue, n):
5
for x in range(1, n+1):
6
# produce an item
7
print(('producing {}/{}'.format(x, n)))
8
# simulate i/o operation using sleep
9
await asyncio.sleep(random.random())
10
item = str(x)
11
# put the item in the queue
12
await queue.put(item)
13
14
15
async def consume(queue):
16
while True:
17
# wait for an item from the producer
18
item = await queue.get()
19
if item is None:
20
# producer emits None to indicate that it is done
21
break
22
23
# process the item
24
25
print(("consuming item {}...".format(item)))
26
# simulate the i/o operation using sleep
27
await asyncio.sleep(random.random())
28
29
loop = asyncio.get_event_loop()
30
queue = asyncio.Queue(loop=loop)
31
producer_coro = produce(queue, 10)
32
consumer_coro = consume(queue)
33
34
loop.run_until_complete(asyncio.gather(producer_coro, consumer_coro))
35
loop.close()
36
37