我创建了一个在ctor(__init__
)中启动新线程的类
并在dtor(__del__
)中加入了线程
像这样:
import threading
import time
class Dthread:
m_thread: threading.Thread
def __init__(self, interval=1):
self.interval = interval
self.m_thread = threading.Thread(target=self.run, args=())
self.m_thread.daemon = True
self.m_thread.start()
def __del__(self):
self.m_thread.join()
def run(self):
while True:
print('Doing something important in the background')
time.sleep(self.interval)
g = Dthread(True)
print('Checkpoint')
print('Bye')
我在“main function”启动后要继续运行的线程是什么,但是当我在IDE中运行此代码时,我得到了:Doing something important in the background
Checkpoint
Bye
当我在repl.it中运行它时我得到:
Doing something important in the background
Checkpoint
Bye
Doing something important in the background
Doing something important in the background
Doing something important in the background ...
最佳答案
如果从命令行运行,则程序将按预期运行。因此,我猜测您是在IDE或jupyter笔记本或类似的东西中运行的,没有真正的退出处理发生,因此守护进程线程被终止。我已经对该程序进行了修改,使其具有一个单独的Runner
类,其中包含重要的代码。它将检查stop
条件,并在其run
方法中终止其循环,以便实际上可以连接线程(您在原始代码中拥有的join
调用实际上对于多余的守护进程线程是多余的,当存在非非守护程序线程离开,并且由于run
方法永不返回而将永远无法完成)。
此Runner
类需要与Dthread类分开,Dthread类的析构函数调用Runner
类的stop
方法,然后加入线程。这是因为我发现当线程在当前正在运行析构函数的同一实例上运行方法时,它不起作用。注意,我还通过将实例设置为Dthread
并强制进行垃圾回收来确保调用None
实例的析构函数。当然,您可以直接在join
实例上直接调用Dthread
方法。
import threading
import time
import gc
class Dthread:
m_thread: threading.Thread
class Runner():
def __init__(self, interval):
self._interval = interval
self._stop = False
def run(self):
while not self._stop:
print('Doing something important in the background')
time.sleep(self._interval)
def stop(self):
self._stop = True
def __init__(self, interval=1):
self.stop = False
self.joined = False
self.runner = Dthread.Runner(interval)
self.m_thread = threading.Thread(target=self.runner.run, args=())
#self.m_thread.daemon = True
self.m_thread.start()
def __del__(self):
print('dtor called.')
self.join()
def join(self):
if not self.joined:
self.runner.stop()
self.m_thread.join()
self.joined = True
g = Dthread(1.0)
print('Checkpoint')
print('Bye')
g = None # or g.join()
gc.collect()
关于python - 在dtor python上加入线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64662967/