当前位置:  开发笔记 > 编程语言 > 正文

大多数Pythonic方式在一段时间后杀死一个线程

如何解决《大多数Pythonic方式在一段时间后杀死一个线程》经验,为你挑选了1个好方法。



1> 小智..:

在这种情况下使用事件可以很好地作为信令机制,并且实际上在线程模块文档中推荐使用.

如果您希望线程正常停止,请使它们成为非守护进程并使用合适的信令机制,例如Event.

验证线程终止时,超时几乎总是会引入错误空间.因此,虽然使用.join()带有超时的初始决策来触发事件是正常的,但最终验证应该使用 .join()没有超时的情况.

# 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()

推荐阅读
mobiledu2402852413
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有