Threading in Python
In this section, we are going to discuss the concept of threading in Python. We will be making use of threading in the next chapter. Threads enable running multiple processes at the same time. For example, we can run motors while listening to incoming events from sensors. Let's demonstrate this with an example.
We are going to emulate a situation where we would like to process events from sensors of the same type. In this example, we are just going to print something to the screen. We need to define a function that listens to events from each sensor:
def sensor_processing(string): for num in range(5): time.sleep(5) print("%s: Iteration: %d" %(string, num))
We can make use of the preceding function to listen for sensor events from three different sensors at the same time using the threading
module in Python:
thread_1 = threading.Thread(target=sensor_processing, args=("Sensor 1",)) thread_1.start() thread_2 = threading.Thread(target=sensor_processing, args=...