Python 杀死线程

发布于 2024-09-25 08:17:24 字数 297 浏览 0 评论 0原文

我正在尝试杀死 python 中的一个线程。例外将是执行此操作的首选方法,因为通过 try:except: 对优雅退出线程的 run 方法将允许关闭资源。

我尝试过:有什么方法可以杀死线程Python? ,但指定在代码执行系统调用(如 time.sleep)时不起作用。有没有办法在另一个线程(或进程,不介意)中引发异常,无论线程正在执行什么,该异常都可以工作?

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.

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等风也等你 2024-10-02 08:17:24

一般来说,引发异步异常很难正确处理。这是因为,不是具有可能生成异常的单个特定代码点(因此需要测试异常处理),而是可能在任何字节码指令之后生成异常。这使得实现和全面测试异常处理变得更加困难。

也就是说,这是可以做到的,但目前在 Python 中并不安全。在 Python 中异步引发异常是危险的,因为您可能在异常处理程序期间引发该异常,这将引发另一个异常并阻止正确进行清理。请参阅我的答案:如何限制 Python 中函数调用的执行时间

可以发出取消某些形式睡眠的信号,但 Python 中没有通用的基础设施。您最好避免杀死线程,或者将线程移动到进程,您可以在其中向整个进程发送信号并干净地退出。

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.

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.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文