杀死阻塞线程
Killing a blocking thread
我在尝试开发一个线程应用程序时遇到了困难,其中每个线程都通过网络进行 REST 调用。
我需要在特定超时后终止活动线程。我已经尝试了这里看到的所有 python 2.7.x 方法,但无法正常工作。
我在 OEL linux (3.8.13-44.1.1.el6uek.x86_64) 上使用 python 2.7.6。
这是一个简化的代码片段:
class cthread(threading.Thread):
def __init__(self, cfg, host):
self.cfg = cfg
self.host = host
self.runf = False
self.stop = threading.Event()
threading.Thread.__init__(self. target=self.collect)
def terminate(self):
self.stop.set()
def collect(self):
try:
self.runf = True
while (not self.stop.wait(1)):
# Here I do urllib2 GET request to a REST service which could hang
<rest call>
finally:
self.runf = False
timer_t1 = 0
newthr = cthread(cfg, host)
newthr.start()
while True:
if timer_t1 > 600:
newthr.terminate()
break
time.sleep(30)
timer_t1 += 30
基本上在我的超时期限之后,我需要终止所有剩余的线程,无论是否优雅。
还没来得及让它工作。
我的做法是否正确?
没有官方 API 可以终止 python 中的线程。
在依赖 urllib2 的代码中,您可能会定期将线程的超时时间从主循环传递给 运行 并使用 urllib2 与 timeout 选项。或者甚至跟踪线程中的计时器,利用与 urllib2 相同的方法。
我在尝试开发一个线程应用程序时遇到了困难,其中每个线程都通过网络进行 REST 调用。
我需要在特定超时后终止活动线程。我已经尝试了这里看到的所有 python 2.7.x 方法,但无法正常工作。
我在 OEL linux (3.8.13-44.1.1.el6uek.x86_64) 上使用 python 2.7.6。
这是一个简化的代码片段:
class cthread(threading.Thread):
def __init__(self, cfg, host):
self.cfg = cfg
self.host = host
self.runf = False
self.stop = threading.Event()
threading.Thread.__init__(self. target=self.collect)
def terminate(self):
self.stop.set()
def collect(self):
try:
self.runf = True
while (not self.stop.wait(1)):
# Here I do urllib2 GET request to a REST service which could hang
<rest call>
finally:
self.runf = False
timer_t1 = 0
newthr = cthread(cfg, host)
newthr.start()
while True:
if timer_t1 > 600:
newthr.terminate()
break
time.sleep(30)
timer_t1 += 30
基本上在我的超时期限之后,我需要终止所有剩余的线程,无论是否优雅。
还没来得及让它工作。
我的做法是否正确?
没有官方 API 可以终止 python 中的线程。
在依赖 urllib2 的代码中,您可能会定期将线程的超时时间从主循环传递给 运行 并使用 urllib2 与 timeout 选项。或者甚至跟踪线程中的计时器,利用与 urllib2 相同的方法。