-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathqueue_example.py
49 lines (43 loc) · 1022 Bytes
/
queue_example.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
from time import sleep
from random import random
from threading import Thread
from queue import Queue
# generate work
def producer(queue):
print('Producer: Running')
# generate work
for i in range(10):
# generate a value
value = random()
# block
sleep(value)
# add to the queue
queue.put(value)
# all done
queue.put(None)
print('Producer: Done')
# consume work
def consumer(queue):
print('Consumer: Running')
# consume work
while True:
# get a unit of work
item = queue.get()
# check for stop
if item is None:
break
# report
print(f'>got {item}')
# all done
print('Consumer: Done')
# create the shared queue
queue = Queue()
# start the consumer
consumer = Thread(target=consumer, args=(queue,))
consumer.start()
# start the producer
producer = Thread(target=producer, args=(queue,))
producer.start()
# wait for all threads to finish
producer.join()
consumer.join()