如何在下面的類守護程式中進行踩踏,以便在程式結束后停止?
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')
uj5u.com熱心網友回復:
您應該添加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')
uj5u.com熱心網友回復:
另一種方法 - 在呼叫后將其設定為守護行程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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/409604.html
標籤:
上一篇:使用OpenMP對陣列進行排序:為什么一些隨機陣列以長數字結尾并且沒有正確排序?
下一篇:子執行緒看不到主執行緒增加的效果
