python线程超时kill,一段时间后杀死线程的大多数Python方法

小编典典

在这种情况下,使用事件作为信号传递机制就可以了,实际上在线程模块docs中建议使用。

如果您希望线程正常停止,请使其成为非守护进程,并使用适当的信号传递机制,例如Event。

验证线程终止时,超时几乎总是会引入错误空间。因此,虽然将.join()with超时用于触发事件的初始决策是可以的,但最终验证应使用.join()没有超时的a

进行。

# wait 30 seconds for the thread to finish its work

t.join(30)

if t.is_alive():

print "thread is not done, setting event to kill thread."

e.set()

# The thread can still be running at this point. For example, if the

# thread's call to isSet() returns right before this call to set(), then

# the thread will still perform the full 1 second sleep and the rest of

# the loop before finally stopping.

else:

print "thread has already finished."

# Thread can still be alive at this point. Do another join without a timeout

# to verify thread shutdown.

t.join()

可以简化为以下形式:

# Wait for at most 30 seconds for the thread to complete.

t.join(30)

# Always signal the event. Whether the thread has already finished or not,

# the result will be the same.

e.set()

# Now join without a timeout knowing that the thread is either already

# finished or will finish "soon."

t.join()

2020-12-20

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值