Python杀死线程 [英] Python kill thread

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

问题描述

我正在尝试杀死python中的线程.最好是使用异常,因为通过try:except:对可以正常退出线程的run方法.

I'm trying to kill a thread in python. An exception would be the preferred way to do it, as a graceful exit of the run method of the thread through a try:except: pair would allow to close resources.

我尝试过:是否有任何方法可以杀死,但是它指定在代码执行系统调用(例如time.sleep)时不起作用.有没有一种方法可以在另一个线程(或进程,不要介意)中引发一个异常,而该异常不会影响该线程正在执行什么?

I tried : Is there any way to kill a Thread in Python? , but is specifies that is doesn't work while the code is executing a system call (like time.sleep). Is there a way to raise an exception in another thread (or process, in don't mind,) that work no mater what the thread is executing?

推荐答案

通常,引发异步异常很难正确处理.这是因为,不是在单个特定的代码点上可能会生成异常的地方(因此需要测试异常处理的地方),而是在 any 个字节码指令之后生成了异常.这使得实施和全面测试异常处理变得更加困难.

In general, raising asynchronous exceptions is difficult to handle properly. This is because, rather than having single, specific points of code where an exception may be generated--and therefore where exception handling needs to be tested--instead, an exception may be generated after any bytecode instruction. This makes it much harder to implement and fully test exception handling.

那是可以做到的,但是目前在Python中并不安全.在Python中异步引发异常是很危险的,因为您可能在异常处理程序期间引发异常,这将引发另一个异常并阻止清理工作正常进行.请参阅如何限制Python中函数调用的执行时间.

That said, it can be done--but, presently, not safely in Python. Raising an exception asynchronously in Python is dangerous, because you might raise it during an exception handler, which will raise another exception and prevent cleanup from occurring properly. See my answer at How to limit execution time of a function call in Python.

可以发出某种形式的睡眠来取消信号,但是Python中没有通用的基础架构.最好避免避免杀死线程,或者将线程移到进程,在该进程中您可以向整个进程发送信号并干净地退出.

It's possible to signal some forms of sleep to cancel, but there's no general infrastructure for this in Python. You're much better off either avoiding the need to kill a thread, or moving the thread to a process, where you can send a signal to the whole process and exit cleanly.

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

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