当使用类Pup创建在后台运行的可停止线程时,直到调用.stop()为止:
pup.join()没有在pup.stop()后面被调用时会发生什么?以下情况会导致泄漏吗?pup = Pup() pup.start() time.sleep(5) pup.stop() pup2 = Pup()傀儡2.() time.sleep(5)傀儡2.停止( pup3 )pup3= Pup()傀儡3. time.sleep(5)木偶3.停止()
下面的主要代码是从this SO answer借来的
import time
import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stopper = threading.Event()
def stop(self):
self._stopper.set()
def stopped(self):
return self._stopper.isSet()
class Pup(StoppableThread):
def __init__(self, i, *args, **kwargs):
super(Pup, self).__init__(*args, **kwargs)
self.i = i
def run(self):
while True:
if self.stopped():
return
print("Hello, world!", i)
time.sleep(1)
for i in range(100):
pup = Pup(i)
pup.start()
time.sleep(5)
pup.stop()发布于 2020-07-02 07:30:59
StoppableThread应该是join编辑的。
因为它只是一个关于threading.Thread的薄薄的包装器,所以您可以设置和检查标志stopper。
在这种情况下,必须有定期检查此标志的代码。检查之间的延迟量取决于类的用户。考虑到假定线程应该正确停止,您必须使用join。因为如果您将线程设置为daemon,并试图在应用程序完成之前停止它:
守护进程线程在关机时突然停止。它们的资源(如打开的文件、数据库事务等)可能不能正常释放。如果您想让您的线程优雅地停止,请将它们设置为非守护进程,并使用适当的信号机制,例如事件。
只有当您的代码负责检查
join也没有被调用,将等待所有非守护进程线程的完成。但是使用join可以更好地控制程序流。StoppableThread变成daemon是个坏主意。https://stackoverflow.com/questions/62689369
复制相似问题