我有一个应用程序,它依赖于一些阻塞操作的超时信号。
例如:
def wait_timeout(signum, frame):
raise Exception("timeout")
signal.signal(signal.SIGALRM, wait_timeout)
signal.setitimer(signal.ITIMER_REAL, 5)
try:
while true:
print("zzz")
sleep(1)
except Exception as e:
# timeout
print("Time's up")现在,我已经使用相同的方法实现了多线程,但是对于所有的线程,我得到了ValueError: signal only works in main thread。
我假设使用信号超时的方法不适用于线程。
不幸的是,我不能用这样的东西:
timeout = 5
start = time.time()
while true:
print("zzz")
sleep(1)
if time.time() <= start+timeout:
print("Time's up)
break因为while循环中的操作可能是阻塞的,并且可能永远持续,因此循环可能永远不会到达if子句。
Q:如何在线程中实现超时,就像我过去用信号做的那样?
编辑:我遇到了这篇博客文章,展示了一个类似于setTimeout()在python中JavaScript中的解决方案。我认为这可能是一种可能的解决方案,但我真的不确定如何使用它。
edit2:我主要按照以下方式启动线程:
p = Popen(["tool", "--param", arg], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
t = Thread(target=process_thread, daemon=True, args=(p,arg1,arg2))
t.start()process_thread函数通过执行以下操作来处理tool的标准输出:
for line in p.stdout:
# process line of the processes stdout这个过程可能要花费很长时间,例如,一旦tool不产生任何输出。我只想要tool的输出,比如说5秒,所以在特定的超时之后,for循环需要中断。
这就是我所用的信号,但很明显它们在线程中不起作用。
edit3:我已经创建了一个更详细、更准确的示例,说明我打算如何在线程中使用这些单数。看这里的要点
发布于 2017-03-07 15:28:23
您正在寻找的是一个看门狗。
def watchdog(queue):
while True:
watch = queue.get()
time.sleep(watch.seconds)
try:
watch = queue.get_nowait()
# No except, got queue message,
# do noting wait for next watch
except queue.Empty:
os.kill(watch.pid, signal.SIGKILL)
def workload_thread(queue):
pid = os.getpid()
queue.put({'pid':pid, 'seconds':5})
# do your work
# Test Watchdog
# time.sleep(6)
queue.put({'pid':pid, 'done':True})注意:代码未被测试,可能有语法错误!
发布于 2017-03-08 09:42:49
这实现了一个class Terminator,它在给定的timeout=5之后向Threads Popen process发送一个timeout=5。多个不同的pid是可能的。
class Terminator(object):
class WObj():
def __init__(self, process, timeout=0, sig=signal.SIGABRT):
self.process = process
self.timeout = timeout
self.sig = sig
def __init__(self):
self.__queue = queue.Queue()
self.__t = Thread(target=self.__sigterm_thread, args=(self.__queue,))
self.__t.start()
time.sleep(0.1)
def __sigterm_thread(self, q):
w = {}
t = 0
while True:
time.sleep(0.1);
t += 1
try:
p = q.get_nowait()
if p.process == 0 and p.sig == signal.SIGTERM:
# Terminate sigterm_thread
return 1
if p.process.pid not in w:
if p.timeout > 0 and p.sig != signal.SIGABRT:
w[p.process.pid] = p
else:
if p.sig == signal.SIGABRT:
del (w[p.process.pid])
else:
w[p.process.pid].timeout = p.timeout
except queue.Empty:
pass
if t == 10:
for key in list(w.keys()):
p = w[key]
p.timeout -= 1
if p.timeout == 0:
""" A None value indicates that the process hasn't terminated yet. """
if p.process.poll() == None:
p.process.send_signal(p.sig)
del (w[p.process.pid])
t = 0
# end if t == 10
# end while True
def signal(self, process, timeout=0, sig=signal.SIGABRT):
self.__queue.put(self.WObj(process, timeout, sig))
time.sleep(0.1)
def close(self, process):
self.__queue.put(self.WObj(process, 0, signal.SIGABRT))
time.sleep(0.1)
def terminate(self):
while not self.__queue.empty():
trash = self.__queue.get()
if self.__t.is_alive():
self.__queue.put(self.WObj(0, 0, signal.SIGTERM))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.__del__()
def __del__(self):
self.terminate() 例如,这就是工作负载:
def workload(n, sigterm):
print('Start workload(%s)' % n)
arg = str(n)
p = Popen(["tool", "--param", arg], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
sigterm.signal(p, timeout=4, sig=signal.SIGTERM)
while True:
for line in p.stdout:
# process line of the processes stdout
print(line.strip())
time.sleep(1)
if p.poll() != None:
break
sigterm.close(p)
time.sleep(0.1)
print('Exit workload(%s)' % n)
if __name__ == '__main__':
with Terminator() as sigterm:
p1 = Thread(target=workload, args=(1, sigterm)); p1.start(); time.sleep(0.1)
p2 = Thread(target=workload, args=(2, sigterm)); p2.start(); time.sleep(0.1)
p3 = Thread(target=workload, args=(3, sigterm)); p3.start(); time.sleep(0.1)
p1.join(); p2.join(); p3.join()
time.sleep(0.5)
print('EXIT __main__')用Python:3.4.2和Python2.7.9测试
https://stackoverflow.com/questions/42647772
复制相似问题