python守护进程去中断子进程_Python2:守护进程线程不会在键盘中断时被终止

请注意以下解决方案仅适用于

daemon

线程,因为如果将

join

在上面。如果你不把

参加

在非守护进程线程中,如果主服务器退出,它们将继续在后台运行,这是预期的行为。

我的问题是为了

守护进程

线。下面是解决办法。

#一:

不要在线程上放置连接,因为它会导致线程阻塞主进程。工作是因为

守护进程

当主程序退出时,线程退出,因此当您不放置

参加

那你就不用等主程序了

time.sleep(1)

里面

while

只是为了确保

守护进程

线程继续执行,一旦我点击

ctrl-c

主会退出

守护进程

穿上它。

if __name__ == "__main__":

try:

threads = [threading.Thread(name='daemon', target=daemon)

for _ in range(8)]

for th in threads:

th.daemon = True

th.start()

while True:

time.sleep(1)

# signal.pause() # This worked fine for me on Linux, on Windows it doesn't work, not sure about Mac. I am not recommending this because of platform dependency.

except KeyboardInterrupt:

#二:

如果你想

参加

在线程上,对其使用timeout,然后将其保持在

虽然

循环检查直到

thread

alive

. 这将继续检查每个线程

threads

列出它,直到它还活着,然后等待1秒执行它。从现在起

虽然

情况会是

True

直到

Thread

实际上是在它完成之后收获的;它将以1秒为单位的小块阻塞主程序,并且一旦您点击

ctrl-c键

这个

daemon thread

不再活着,因此主程序退出。

if __name__ == "__main__":

try:

threads = [threading.Thread(name='daemon', target=daemon)

for _ in range(8)]

for th in threads:

th.daemon = True

th.start()

for th in threads:

while th.isAlive():

th.join(1)

except KeyboardInterrupt:

print('ctrl-c')

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值