[Tutor] Thread Object integration with GPIO
Steven D'Aprano
steve at pearwood.info
Sun Apr 30 08:00:24 EDT 2017
On Sat, Apr 29, 2017 at 06:26:28PM +0000, Marc Eymard wrote:
> The way I have decided to go about implementing the sensor reading is by
> creating a Thread object and update the distance attribute of this very
> same object from the run() function. The idea is to encapsulate the
> distance reading within the sensor object as much as possible by i.
> creating a sensor/thread object and by ii. avoiding global variables.
That's not a bad approach, but I'd take it one step further: move all
the logic into another object, and just have the thread call it. That
lets you change your mind later, and replace threads with an external
process, or async code, or whatever technology is best. It also allows
you to add whatever smarts or features you need into the object
collecting values, without the thread needing to care about it.
Something like this untested code:
from threading import Thread
class Collector(object):
# Object to collect readings.
def __init__(self):
self.values = []
def store(self, value):
# If you need any data validation or other processing,
# put it here.
self.values.append(value)
def run(self):
print("Starting collecting...")
while True:
value = ... # collect the data somehow
if value == -1:
# No more data?
break
self.store(value)
print("...finished collecting.")
def report(self):
print("I have %d values" % len(self.values))
Now, you can have your main function create a Collector, pass it to the
thread, and process it as needed:
def main():
c = Collector()
t = Thread(target=c.run, name='my thread')
t.start()
t.join()
c.report()
> Attached the script I have come up with
Alas, this mailing list doesn't accept attachments. You should reduce
the script to the smallest amount of code you can, and re-post it,
together with the entire stack trace of the errors.
--
Steve
More information about the Tutor
mailing list