- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson05_queue.py
More file actions
Latest commit
45 lines (41 loc) · 1.09 KB
/
Copy pathlesson05_queue.py
File metadata and controls
45 lines (41 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# SuperFastPython.com
# example of producer/consumer connected via a queue
fromrandomimportrandom
importasyncio
# coroutine to generate work
asyncdefproducer(queue):
print('Producer: Running')
# generate work
for_inrange(10):
# generate a value
value=random()
# suspend to simulate work
awaitasyncio.sleep(value)
# add to the queue
awaitqueue.put(value)
# send an all done signal
awaitqueue.put(None)
print('Producer: Done')
# coroutine to consume work
asyncdefconsumer(queue):
print('Consumer: Running')
# consume work
whileTrue:
# get a unit of work
item=awaitqueue.get()
# check for stop signal
ifitemisNone:
break
# report
print(f'>got {item}')
# all done
print('Consumer: Done')
# entry point coroutine
asyncdefmain():
# create the shared queue
queue=asyncio.Queue()
# run the producer and consumers
awaitasyncio.gather(
producer(queue), consumer(queue))
# start the asyncio program
asyncio.run(main())