How To Get The Number Of Active Threads Started By Specific Class?
code looks like below: class workers1(Thread): def __init__(self): Thread.__init__(self) def run(self): # ...do some stuff class workers2(Thread): def
Solution 1:
This is a minor modification of Doug Hellman's multiprocessing ActivePool example code (to use threading). The idea is to have your workers register themselves in a pool, unregister themselves when they finish, using a threading.Lock to coordinate modification of the pool's active list:
import threading
import time
import random
classActivePool(object):
def__init__(self):
super(ActivePool, self).__init__()
self.active=[]
self.lock=threading.Lock()
defmakeActive(self, name):
with self.lock:
self.active.append(name)
defmakeInactive(self, name):
with self.lock:
self.active.remove(name)
defnumActive(self):
with self.lock:
returnlen(self.active)
def__str__(self):
with self.lock:
returnstr(self.active)
defworker(pool):
name=threading.current_thread().name
pool.makeActive(name)
print'Now running: %s' % str(pool)
time.sleep(random.randint(1,3))
pool.makeInactive(name)
if __name__=='__main__':
poolA=ActivePool()
poolB=ActivePool()
jobs=[]
for i inrange(5):
jobs.append(
threading.Thread(target=worker, name='A{0}'.format(i),
args=(poolA,)))
jobs.append(
threading.Thread(target=worker, name='B{0}'.format(i),
args=(poolB,)))
for j in jobs:
j.daemon=True
j.start()
while threading.activeCount()>1:
for j in jobs:
j.join(1)
print'A-threads active: {0}, B-threads active: {1}'.format(
poolA.numActive(),poolB.numActive())
yields
Nowrunning: ['A0']Nowrunning: ['B0']Nowrunning: ['A0', 'A1']Nowrunning: ['B0', 'B1']Nowrunning: ['A0', 'A1', 'A2']Nowrunning: ['B0', 'B1', 'B2']Nowrunning: ['A0', 'A1', 'A2', 'A3']Nowrunning: ['B0', 'B1', 'B2', 'B3']Nowrunning: ['A0', 'A1', 'A2', 'A3', 'A4']Nowrunning: ['B0', 'B1', 'B2', 'B3', 'B4']A-threadsactive: 4, B-threadsactive: 5A-threadsactive: 2, B-threadsactive: 5A-threadsactive: 0, B-threadsactive: 3A-threadsactive: 0, B-threadsactive: 3A-threadsactive: 0, B-threadsactive: 3A-threadsactive: 0, B-threadsactive: 3A-threadsactive: 0, B-threadsactive: 3A-threadsactive: 0, B-threadsactive: 0A-threadsactive: 0, B-threadsactive: 0A-threadsactive: 0, B-threadsactive: 0
Solution 2:
You can use a semaphore for each class and get their counts: see link.
Post a Comment for "How To Get The Number Of Active Threads Started By Specific Class?"