终端运行python文件、关闭窗口如何结束线程_如何停止终端进程运行包括线程在内的代码?...

守护程序线程

简单地使用守护进程线程来解决这个问题是很有诱惑力的,当只剩下守护进程线程时,python的执行将停止,并且不允许它们很好地清理。The docs把这个说清楚:Daemon threads are abruptly stopped at shutdown. Their resources (such as open files, database transactions, etc.) may not be released properly. If you want your threads to stop gracefully, make them non-daemonic and use a suitable signalling mechanism such as an Event.

让我们听从他们的建议,利用一个事件。在

使用事件

事件是一个简单的标志,可以安全地跨线程设置和读取。在本例中,我们将在主线程中创建一个事件,生成一个新线程来执行一些工作,并监听该事件标志,以防它停止工作。在import threading

ended = threading.Event()

def do_work():

while not ended.is_set():

# Do your repeated work

pass

# Let's create and start our worker thread!

new_thread = threading.Thread(target=do_work)

new_thread.start()

try:

while not ended.is_set():

ended.wait(1)

except (KeyboardInterrupt, SystemExit):

print("Cancelling")

ended.set()

这里的try/catch块在主线程中运行,监听KeyboardInterrupt或SystemExit异常。如果它捕捉到一个,它将设置stopped标志,允许线程完成其当前的循环迭代,并执行它需要的任何清理。在

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值