I have the following scenario (for reference, I want to implement the UCI chess engine protocol):
I need to perform a calculation for some time x
(possibly infinite). When the time is up, I want to know the current state (intermediate result) of the calculation. Additionally, I want to have some kind of stop
command, which interrupts the calculation and returns the current state. Preferably, I would like to send a signal to the calculation that it should come to an end as soon as possible, instead of directly interrupting it. Moreover, the main tread should never block, but always take user input (from the command line). This user input should be processed without affecting the calculation, except when the stop
signal described above is triggered.
How do I implement this in Python?
Since the main thread should listen for user input independently of the calculation, I think that the calculation should run in a separate process. One idea of implementing a timer and stop signal would be to split the calculation into parts that execute very quickly and check if it should stop in between.
timer = start_timer()
while True:
current_result = do_next_calculation_step()
if stop_signal_recieved or timer.time_is_up():
break
return current_result
However, this appears quite inflexible, as it can be difficult to define do_next_calculation_step
in such a way that its execution time is short.