我有timeout
上下文管理器,它与信号完美配合,但它在多线程模式下引发错误,因为信号只在主线程中工作。
def timeout_handler(signum, frame):
raise TimeoutException()
@contextmanager
def timeout(seconds):
old_handler = signal.signal(signal.SIGALRM, timeout_handler)
signal.alarm(seconds)
try:
yield
finally:
signal.alarm(0)
signal.signal(signal.SIGALRM, old_handler)
我见过装饰器实现,timeout
但我不知道如何yield
在派生自threading.Thread
. 我的变种不起作用。
@contextmanager
def timelimit(seconds):
class FuncThread(threading.Thread):
def run(self):
yield
it = FuncThread()
it.start()
it.join(seconds)
if it.isAlive():
raise TimeoutException()