forked from realpython/materials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprodcom_event.py
More file actions
executable file
·82 lines (66 loc) · 2.59 KB
/
Copy pathprodcom_event.py
File metadata and controls
executable file
·82 lines (66 loc) · 2.59 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
import concurrent.futures
import logging
import random
import threading
import time
class Pipeline:
"""
Class to allow a single element pipeline
between producer and consumer.
"""
def __init__(self):
self.value = 0
self._set_lock = threading.Lock()
self._get_lock = threading.Lock()
self._get_lock.acquire()
def get_value(self, name):
logging.debug("%s:about to acquire getlock", name)
self._get_lock.acquire()
logging.debug("%s:have getlock", name)
value = self.value
logging.debug("%s:about to release setlock", name)
self._set_lock.release()
logging.debug("%s:setlock released", name)
return value
def set_value(self, value, name):
logging.debug("%s:about to acquire setlock", name)
self._set_lock.acquire()
logging.debug("%s:have setlock", name)
self.value = value
logging.debug("%s:about to release getlock", name)
self._get_lock.release()
logging.debug("%s:getlock released", name)
def producer(pipeline, event):
"""Pretend we're getting a number from the network."""
while not event.is_set():
new_datapoint = random.randint(1, 101)
# Sleep to simulate waiting for data from network
# time.sleep(float(new_datapoint)/100)
logging.info("Producer got data %d", new_datapoint)
pipeline.set_value(new_datapoint, "Producer")
if event.is_set():
logging.info("Producer received internal event. Exiting")
# don't put sleep here as this will cause the system to stall when the
# consumer is active. That will result in deadlock.
# time.sleep(float(new_datapoint)/100)
logging.info("Producer received event. Exiting")
def consumer(pipeline, event):
"""Pretend we're saving a number in the database."""
datapoint = 0
while not event.is_set():
datapoint = pipeline.get_value("Consumer")
logging.info("Consumer storing data: %d", datapoint)
logging.info("Consumer received event. Exiting")
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
# logging.getLogger().setLevel(logging.DEBUG)
pipeline = Pipeline()
event = threading.Event()
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
executor.submit(producer, pipeline, event)
executor.submit(consumer, pipeline, event)
time.sleep(0.1)
logging.info("Main: about to set event")
event.set()