import _thread import signal import time def alarm_interrupt(sig, frame): raise KeyboardInterrupt # Mimic receiving a SIGINT (KeyboardInterrupt) with SIGALRM while stuck # in a deadlock. # XXX this test can fail when the legacy (non-semaphore) implementation # of locks is used in thread_pthread.h, see issue #11223. oldalrm = signal.signal(signal.SIGALRM, alarm_interrupt) try: lock = _thread.allocate_lock() lock.acquire() signal.alarm(1) t1 = time.time() try: lock.acquire(timeout=5) except KeyboardInterrupt: pass else: raise Exception("KeyboardInterrupt not raised!") dt = time.time() - t1 # Checking that KeyboardInterrupt was raised is not sufficient. # We want to assert that lock.acquire() was interrupted because # of the signal, not that the signal handler was called immediately # after timeout return of lock.acquire() (which can fool assertRaises). if dt > 3.0: raise Exception("dt > 3: dt=%s" % dt) finally: signal.signal(signal.SIGALRM, oldalrm)