如何杀死python中的线程 [英] How can I kill a thread in python

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

问题描述

我使用以下代码启动线程.

I start a thread using the following code.

t = thread.start_new_thread(myfunction)

如何杀死另一个线程中的线程t.因此,基本上从代码上来说,我希望能够做到这一点.

How can I kill the thread t from another thread. So basically speaking in terms of code, I want to be able to do something like this.

t.kill()

请注意,我正在使用Python 2.4.

Note that I'm using Python 2.4.

推荐答案

如果您的线程正忙于执行Python代码,那么您将面临比无法杀死它更大的问题. GIL会阻止其他任何线程运行您用来执行杀死操作的任何指令.(经过一些研究,我了解到解释器会定期释放GIL,因此前面的语句是虚假的.不过,其余的评论仍然有效.)

If your thread is busy executing Python code, you have a bigger problem than the inability to kill it. The GIL will prevent any other thread from even running whatever instructions you would use to do the killing. (After a bit of research, I've learned that the interpreter periodically releases the GIL, so the preceding statement is bogus. The remaining comment stands, however.)

您的线程必须以协作方式编写.也就是说,它必须定期使用诸如信号量之类的信令对象进行检入,主线程可以使用该对象来指示工作线程自愿退出.

Your thread must be written in a cooperative manner. That is, it must periodically check in with a signalling object such as a semaphore, which the main thread can use to instruct the worker thread to voluntarily exit.

while not sema.acquire(False):
    # Do a small portion of work…

或:

for item in work:
    # Keep working…
        # Somewhere deep in the bowels…
        if sema.acquire(False):
            thread.exit()

这篇关于如何杀死python中的线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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