I have the following Python code: class TimeoutException(Exception): pass @contextmanager def time_limit(seconds: float): def signal_handler(signum, frame): global flag flag = True raise TimeoutException("Timed out!") signal.signal(signal.SIGALRM, signal_handler) signal.setitimer(signal.ITIMER_REAL, seconds) try: yield finally: signal.setitimer(signal.ITIMER_REAL, 0) and then # ... prepare deep research with time_limit(max_time): try: while True: self.search(board) except TimeoutException: pass # ... terminate deep research My idea is to perform a deep research calling multiple times the self.search function and then stop after max_time seconds of computation. The code works most of the times, although in some particular cases it doesn't work and it remains in the endless loop. I checked with the debugger using a global flag and I noticed that when the problem occurs the flag is set to True, meaning that the function call to the signal handler happend, but for some reasons the exception raising failed and the execution remained inside the loop. How can I fix this? Continue reading...