I think you do not need threads, but I can misunderstand your requirements, so I will present 2 alternatives.
- Without cutting and dreams
Assuming your current program runs like this:
while True: data = read_sensors() command = process(data) motor_do(command) time.sleep(delay)
Then you can simply delete the dream and only call motor_do if the last call was at least delay seconds ago.
last_call_time = -delay
- With streaming processing (this is an example, I have no experience in streaming / asynchronous use with python 2.7, so there may be better ways to do this)
Assuming your current program runs like this:
while True: data = read_sensors() command = process(data) motor_do(command) // this function sleeps and you CANNOT change it
Then you need to start 1 thread, which will asynchronously invoke engine commands.
import thread command = None command_lock = thread.allocate_lock() def main(): thread.start_new_thread(motor_thread) global command while True: data = read_sensors() with command_lock: command = process(data) def motor_thread(): while True: while not command:
NB: on Unix, time.clock() returns the processor time (= without downtime), so it would be better to use time.time() ... if the system clock is not changed: "Although this function usually returns non-decreasing values "it may return a lower value than the previous one if the system clock was set between two calls." (python 2.7 doc)
I do not know how time.sleep() reacts to changes in the system clock.
see How to get monotonous time durations in python? for exact time delays on unix / py2.7 (and Understanding time.perf_counter () and time.process_time () can be useful)
Python3: just use time.monotonic() ... or time.perf_counter() .
source share