Python:如何终止阻塞线程 [英] Python: How to terminate a blocking thread

查看:1047
本文介绍了Python:如何终止阻塞线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
是否有任何方法可以杀死Python中的线程?

Possible Duplicate:
Is there any way to kill a Thread in Python?

因此,此问题是先前发布的解决方案的后续措施.基本上,它以编程方式终止线程: http://sebulba.wikispaces.com/recipe+thread2

So this question is a follow up to a solution posted previously. Basically it deals with programatically terminating a thread: http://sebulba.wikispaces.com/recipe+thread2

但是它不起作用...,我想知道是否有人可以解释一个人如何终止正在阻塞的线程?我唯一的猜测是我没有提供正确的线程ID,但是我进行了一些测试,并且可以肯定我可以使用iden

However it doesnt work... and I was wondering if someone can explain how one could terminate a thread that is blocking? My only guess is the fact that I am not providing the right thread id, but I did some testing and am pretty sure I can just use iden

如果这是线程ID,我该如何获取正确的线程ID?

If it is the thread ID, how can I go about getting the correct Thread ID?

测试代码:

class BlockingTestThread(Thread):

    def __init__(self):
        self._running_flag = False
        Thread.__init__(self, target=self.test_method)

    def test_method(self):
        try:
            while(not self.stopped()):
                self._running_flag = True
                time.sleep(100)
        finally:
                self._running_flag = False


def _async_raise(tid, exctype):
    '''Raises an exception in the threads with id tid'''
    if not inspect.isclass(exctype):
        raise TypeError("Only types can be raised (not instances)")

    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), ctypes.py_object(exctype))
    time.sleep(0.1)



if __name__ == "__main__":
    thread = BlockingTestThread()
    thread.start()

    _async_raise(thread.ident, SystemExit)
    print "Joining thread"
    thread.join()
    print "Done Joining thread"
    #will never get here!

推荐答案

这里是一种更好的方法,假设您要使用睡眠,请在事件上使用等待"命令.

Here is a better way to do it, use the "wait" command on the event, asssuming you want to use sleep.

class BlockingTestThread(Thread):
    def __init__(self):
        self._running_flag = False
        self.stop  = threading.Event()
        Thread.__init__(self, target=self.test_method)

    def test_method(self):
        try:
            while(not self.stop.wait(1)):
                self._running_flag = True
                print 'Start wait'
                self.stop.wait(100)
                print 'Done waiting'
        finally:
                self._running_flag = False

    def terminate(self):
         self.stop.set()  

if __name__ == "__main__":
    thread = BlockingTestThread()
    thread.start()

    time.sleep(2)
    print 'Time sleep 2'
    thread.terminate()
    print "Joining thread"
    thread.join()
    print "Done Joining thread"

很显然,您需要将阻塞线程包装在使用上述模式的东西中,但是如果您不能做的另一种选择是导致您的进程引发异常,那么在我们的例子中,我们基本上杀死了基础连接,这会导致异常,如果在设置了stop标志的情况下发生该异常,我们将忽略它.

Obviously you are going to need to wrap your blocking thread in something that uses the pattern above, but if you can't the other option is to cause your process to throw an exception, in our case we basically kill the underlying connection, which causes an exception, and when that exception happens if the stopped flag is set, we ignore it.

这篇关于Python:如何终止阻塞线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆