-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlesson05_queue.py
50 lines (47 loc) · 1.36 KB
/
lesson05_queue.py
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
46
47
48
49
50
# SuperFastPython.com
# example of producer and consumer processes with queue
from time import sleep
from random import random
from multiprocessing import Process
from multiprocessing import Queue
# custom function for generating work (producer)
def producer(shared_queue):
print('Producer: Running', flush=True)
# generate work
for _ in range(10):
# generate a value
value = random()
# block
sleep(value)
# add to the queue
shared_queue.put(value)
# all done
shared_queue.put(None)
print('Producer: Done', flush=True)
# custom function for consuming work (consumer)
def consumer(shared_queue):
print('Consumer: Running', flush=True)
# consume work
while True:
# get a unit of work
item = shared_queue.get()
# check for stop
if item is None:
break
# report
print(f'>got {item}', flush=True)
# all done
print('Consumer: Done', flush=True)
# protect the entry point
if __name__ == '__main__':
# create the shared queue
queue = Queue()
# start the consumer
consumer_p = Process(target=consumer, args=(queue,))
consumer_p.start()
# start the producer
producer_p = Process(target=producer, args=(queue,))
producer_p.start()
# wait for all processes to finish
producer_p.join()
consumer_p.join()