Counting Threads
David Poundall
david at jotax.com
Sat Oct 29 03:01:59 EDT 2005
After much optimisation it turns out the following code does the job
for me. In the end using count didn't give me the flexibility I
needed. Instead I now name each thread and track them accordingly.
It's arguable if I need the thread locking now though, however I have
left it in to remind me of the syntax.
Thank you for posting back Dennis. Much appreciated.
# --------------------------------------------------------
class ServerThreads:
"""
Wrapper for thread handling. These threads are not
dynamic, that is to say once the application is fully
loaded the number of threads running is determined
by the size of the application - and is fixed.
"""
# --------------------- Class Attributes
# Dict holds object references to all threads
# created in the server (running or not)
thr_objects = {}
# Dict holds status of all running threads
# 0 = stopped, 1 = running
thr_running = {}
# Lock object
lck = Lock()
def launch(self, ThrName, SubToLaunch,
SubsArgs=(), SubsKwargs={}, AsDaemon=True):
""" Kickoff a thread.
thr_objects : Dictionary using ThreadTitle
as the key which holds
references to the thread object
thr_running : Dictionary holding the status
of each thread
"""
s = ServerThreads
# ---------------------
s.lck.acquire()
try:
t = Thread(name = ThrName, target=SubToLaunch,
args = SubsArgs, kwargs = SubsKwargs)
t.setDaemon(AsDaemon) # Must be set before start
s.thr_objects[ThrName] = t
s.thr_running[ThrName] = 1
if ag.gb_Appdebug: print 'Thread Started ------------- ',
ThrName
t.start()
finally:
s.lck.release()
# ---------------------
def stoprequest(self,thr_name):
""" Thread stop request - stop is pending.
Join is not needed because the main code body
drops out of the thread loops once the
thr_running = true condition has been removed."""
s = ServerThreads
# ---------------------
s.lck.acquire()
s.thr_running[thr_name] = 0 # Flag to tell running
thread to please terminate
if ag.gb_Appdebug: print 'Thread Stopping ----------- ' +
thr_name
s.lck.release()
# ---------------------
def allOK(self):
""" Returns a list of all threads that are down
when they shouldn't be (if any) """
s = ServerThreads
ThreadsDown = []
for thr_name in s.thr_objects:
if not s.thr_objects[thr_name].isAlive() and
s.thr_running[thr_name]:
# If a thread has an unscheduled stop indicate this by
returning the
# threads name otherwise return None.
ThreadsDown.append(thr_name)
return ThreadsDown
More information about the Python-list
mailing list