请注意以下解决方案仅适用于
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')