我有一个上下文管理器
我看到了
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()