I am working on an event-driven state machine. An event handler processes incoming events continuously (while true) in its own thread. Depending on the current state, all possible transitions are checked and a state transition is executed if the event matches. Only the task in the current state is to be executed, therefore with a state transition first the execution of the old state is terminated and then the new state is executed. Since I want to asynchronously terminate a state with a STOP event, the execution of a state runs on a separate thread. However, I have now found out that threads cannot be terminated (also makes sense in order not to generate unsafe states). It would therefore be very nice if I could interrupt the execution of a thread (similar to handling exceptions) by a signal to establish a safe state. Is it possible to throw an exception in a thread externally for this?
from time import sleep
from threading import Thread
class StopEvent(Exception):
pass
class State:
def _task(self):
# Will be executed within the thread
print("Starting state ...")
try:
for i in range(10):
print(i)
sleep(0.5)
except StopEvent:
print("Establish safe state.")
print("Terminate state ...")
def run_task(self):
self._thread = Thread(target=self._task)
self._thread.start()
def stop_task(self):
raise StopEvent
state = State()
state.run_task()
sleep(2)
state.stop_task()
I have only tried the threading package so far. Multiprocessing would give me the possibility to terminate the process, but then the system also can be in an unsafe state. I first had the idea to terminate the state task thread via a thread daemon, but this only works if the entire program ends.