Kill removed threads

main2
Bob Mottram 2019-10-16 16:17:00 +01:00
parent 3b0d441e5b
commit fea921ffec
1 changed files with 23 additions and 3 deletions

View File

@ -10,9 +10,11 @@ import threading
import sys import sys
import trace import trace
import time import time
import datetime
class threadWithTrace(threading.Thread): class threadWithTrace(threading.Thread):
def __init__(self, *args, **keywords): def __init__(self, *args, **keywords):
self.startTime=None
tries=0 tries=0
while tries<3: while tries<3:
try: try:
@ -32,6 +34,7 @@ class threadWithTrace(threading.Thread):
self.__run_backup = self.run self.__run_backup = self.run
self.run = self.__run self.run = self.__run
threading.Thread.start(self) threading.Thread.start(self)
self.startTime=datetime.datetime.utcnow()
break break
except Exception as e: except Exception as e:
print('ERROR: threads.py/start failed - '+str(e)) print('ERROR: threads.py/start failed - '+str(e))
@ -78,11 +81,27 @@ def removeDormantThreads(threadsList: [],debug: bool) -> None:
return return
dormantThreads=[] dormantThreads=[]
currTime=datetime.datetime.utcnow()
# which threads are dormant? # which threads are dormant?
noOfActiveThreads=0 noOfActiveThreads=0
for th in threadsList: for th in threadsList:
removeThread=False
if not th.is_alive(): if not th.is_alive():
if debug:
print('DEBUG: thread is not alive')
removeThread=True
elif not th.startTime:
if debug:
print('DEBUG: thread has no start time')
removeThread=True
elif (currTime-th.startTime).total_seconds()>200:
if debug:
print('DEBUG: thread is too old')
removeThread=True
if removeThread:
dormantThreads.append(th) dormantThreads.append(th)
else: else:
noOfActiveThreads+=1 noOfActiveThreads+=1
@ -94,5 +113,6 @@ def removeDormantThreads(threadsList: [],debug: bool) -> None:
for th in dormantThreads: for th in dormantThreads:
if debug: if debug:
print('DEBUG: Removing dormant thread '+str(dormantCtr)) print('DEBUG: Removing dormant thread '+str(dormantCtr))
dormantCtr+=1 dormantCtr+=1
threadsList.remove(th) threadsList.remove(th)
th.kill()