【发布时间】:2016-08-18 14:59:36
【问题描述】:
我在尝试开发一个线程应用程序时遇到了困难,其中每个线程都通过网络进行 REST 调用。
我需要在某个超时后终止活动线程。我已经尝试了在这里看到的所有 python 2.7.x 方法,但都无法正常工作。
我在 OEL linux (3.8.13-44.1.1.el6uek.x86_64) 上使用 python 2.7.6。
这是一个简化的sn-p代码:
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
基本上在我的超时时间之后,我需要终止所有剩余的线程,无论是否正常。
没有时间让它工作。
我这样做的方法是否正确?
【问题讨论】:
标签: python-2.7 python-multithreading