如何在线程子类守护进程中创建线程?
how to make a thread in a thread subclass daemon?
如何在下面的 class 守护进程中设置线程以便在程序结束后停止?
import threading
import time
class A_Class(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def __del__(self):
print('deleted')
def run(self):
while True:
print("running")
time.sleep(1)
a_obj = A_Class()
a_obj.start()
time.sleep(5)
print('The time is up, the thread should end')
您应该将 daemon=True
添加到您的 Thread.__init__()
:
import threading
import time
class A_Class(threading.Thread):
def __init__(self):
threading.Thread.__init__(self, daemon=True)
def __del__(self):
print('deleted')
def run(self):
while True:
print("running")
time.sleep(1)
a_obj = A_Class()
a_obj.start()
time.sleep(5)
print('The time is up, the thread should end')
另一种方法 - 在调用 super().__init__()
后将其设置为守护进程。
class A_Class(threading.Thread):
def __init__(self):
super().__init__()
self.daemon = True
def __del__(self):
print('deleted')
def run(self):
while True:
print("running", self.isDaemon())
time.sleep(1)
或使用关键字参数:
class A_Class(threading.Thread):
def __init__(self,*args,**kwargs):
super().__init__(**kwargs)
def __del__(self):
print('deleted')
def run(self):
while True:
print("running", self.isDaemon())
time.sleep(1)
a_obj = A_Class(daemon=True)
如何在下面的 class 守护进程中设置线程以便在程序结束后停止?
import threading
import time
class A_Class(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def __del__(self):
print('deleted')
def run(self):
while True:
print("running")
time.sleep(1)
a_obj = A_Class()
a_obj.start()
time.sleep(5)
print('The time is up, the thread should end')
您应该将 daemon=True
添加到您的 Thread.__init__()
:
import threading
import time
class A_Class(threading.Thread):
def __init__(self):
threading.Thread.__init__(self, daemon=True)
def __del__(self):
print('deleted')
def run(self):
while True:
print("running")
time.sleep(1)
a_obj = A_Class()
a_obj.start()
time.sleep(5)
print('The time is up, the thread should end')
另一种方法 - 在调用 super().__init__()
后将其设置为守护进程。
class A_Class(threading.Thread):
def __init__(self):
super().__init__()
self.daemon = True
def __del__(self):
print('deleted')
def run(self):
while True:
print("running", self.isDaemon())
time.sleep(1)
或使用关键字参数:
class A_Class(threading.Thread):
def __init__(self,*args,**kwargs):
super().__init__(**kwargs)
def __del__(self):
print('deleted')
def run(self):
while True:
print("running", self.isDaemon())
time.sleep(1)
a_obj = A_Class(daemon=True)