multithreading - Collecting variables from multiple python scripts in one parent script -
i try write python-parent-script, collects data 4 child-scripts. got:
every child-script reads data different sensor , have read continiously. right read them in while true loops.
different sensors have different response times, 1 child-script reading a, lets say, once second rate while read 100 times faster.
my goal/my struggle:
- collect child-generated data in 1 script, in 4 different variables
what acheved yet:
child-scripts doing there work fine , reading data no issues
i start 4 child-scripts terminal subprocesses no idea how collect ther generated data
pass data between scripts never 2 scripts @ same time , way slow, since 'from script import variable' fast reading of sensor.
later plans sending 4 variables via bluetooth phone, whitch successed allready 1 sensor.
since quite new whole raspberry/python community firstly sorry unspecific explenation. please feel free ask further informations or suggest solve things differently. , secondly appreceate lot if me code-snippets if like, because again quite new , helps me way more links librarys or documenturies create more questions answearing them.
thank lot in advance
the easiest way accomplish using threads, available through threading class. collecting data simple writing shared variable (with thread safety of course).
import threading import time data1 = [] lock1 = threading.lock() # use lock, mutex, or semaphore ensure thread safety def foo(): while true: lock1.acquire() data1.append(bar) lock1.release() time.sleep(10) foo_thread = threading.thread(target=foo) foo_thread.start() while true: lock1.acquire() # if values don't need held in memory parent # script can implement kind of queue , delete values # after processing do_stuff_with(data) lock1.release() # queuing allows parent script run @ slower rate time.sleep(100) the example above quick demonstration of threading. there better data types implement queuing in, such collection.deque.
threading in python have caveats though, namely python runs scripts in 1 single process , there global interpreter lock, meaning threading module provides concurrency, not parallelism. 4 data collections cause issues, if better performance needed multiprocessing provides tools spawning multiple python processes allowing true parallelism.
Comments
Post a Comment