【问题标题】:Killing a blocking thread杀死一个阻塞线程
【发布时间】: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


【解决方案1】:

没有官方 API 可以杀死 python 中的线程。

在您依赖 urllib2 的代码中,您可能会定期传递超时,让您的线程从主循环运行并将 urllib2timeout 选项。甚至可以使用与 urllib2 相同的方法跟踪线程中的计时器。

【讨论】:

  • 我不得不将它转移到使用子进程而不是线程......使用python线程根本没有办法可靠地做到这一点,至少2.7.x python没有。甚至 Perl 在线程方面也比 python 2.7 更好。当然,现在我不得不担心内存占用,因为我正在使用子进程......目前的长期计划是现在将其移至 Java。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多