python杀死子线程,Python杀死线程

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值