【发布时间】:2018-05-23 10:31:49
【问题描述】:
请考虑下面的代码:
#! /usr/bin/env python3
import threading
import time
class MyThread(threading.Thread):
def __init__(self):
super().__init__()
self._quit_flag = False
def run(self):
while not self._quit_flag:
print("Thread is alive!")
time.sleep(0.500)
def request_quit(self):
self._quit_flag = True
mt = MyThread()
mt.start()
将其保存为“test.py”并运行“python3 -i test.py”后,我得到了一个交互式会话,线程定期打印“线程活着!”消息。
当我按下 control-D 或运行 exit() 时,python3 进程不会终止,因为线程仍在运行。我想解决这个问题。
但是,我不想让线程成为守护线程——我希望能够正确地结束/加入线程,因为在我正在解决的现实案例中,我想很好地终止网络连接。
有没有办法做到这一点?例如,在 REPL 循环终止之后,就在主线程退出之前执行的某个钩子可用吗?
【问题讨论】:
-
你知道
atexit吗?
标签: python python-multithreading