code looks like below:
JavaScript
x
20
20
1
class workers1(Thread):
2
def __init__(self):
3
Thread.__init__(self)
4
def run(self):
5
# ...do some stuff
6
7
class workers2(Thread):
8
def __init__(self):
9
Thread.__init__(self)
10
def run(self):
11
# ...do some stuff
12
13
14
if __name__ == "__main__":
15
# start workers
16
17
while True:
18
print "Number of threads active", threading.activeCount()
19
print "Number of worker1 threads", ?????, "Number of worker2 threads", ?????
20
Is there a way to get the number of threads being active by originating class ?
Advertisement
Answer
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:
JavaScript
1
48
48
1
import threading
2
import time
3
import random
4
5
class ActivePool(object):
6
def __init__(self):
7
super(ActivePool, self).__init__()
8
self.active=[]
9
self.lock=threading.Lock()
10
def makeActive(self, name):
11
with self.lock:
12
self.active.append(name)
13
def makeInactive(self, name):
14
with self.lock:
15
self.active.remove(name)
16
def numActive(self):
17
with self.lock:
18
return len(self.active)
19
def __str__(self):
20
with self.lock:
21
return str(self.active)
22
def worker(pool):
23
name=threading.current_thread().name
24
pool.makeActive(name)
25
print 'Now running: %s' % str(pool)
26
time.sleep(random.randint(1,3))
27
pool.makeInactive(name)
28
29
if __name__=='__main__':
30
poolA=ActivePool()
31
poolB=ActivePool()
32
jobs=[]
33
for i in range(5):
34
jobs.append(
35
threading.Thread(target=worker, name='A{0}'.format(i),
36
args=(poolA,)))
37
jobs.append(
38
threading.Thread(target=worker, name='B{0}'.format(i),
39
args=(poolB,)))
40
for j in jobs:
41
j.daemon=True
42
j.start()
43
while threading.activeCount()>1:
44
for j in jobs:
45
j.join(1)
46
print 'A-threads active: {0}, B-threads active: {1}'.format(
47
poolA.numActive(),poolB.numActive())
48
yields
JavaScript
1
21
21
1
Now running: ['A0']
2
Now running: ['B0']
3
Now running: ['A0', 'A1']
4
Now running: ['B0', 'B1']
5
Now running: ['A0', 'A1', 'A2']
6
Now running: ['B0', 'B1', 'B2']
7
Now running: ['A0', 'A1', 'A2', 'A3']
8
Now running: ['B0', 'B1', 'B2', 'B3']
9
Now running: ['A0', 'A1', 'A2', 'A3', 'A4']
10
Now running: ['B0', 'B1', 'B2', 'B3', 'B4']
11
A-threads active: 4, B-threads active: 5
12
A-threads active: 2, B-threads active: 5
13
A-threads active: 0, B-threads active: 3
14
A-threads active: 0, B-threads active: 3
15
A-threads active: 0, B-threads active: 3
16
A-threads active: 0, B-threads active: 3
17
A-threads active: 0, B-threads active: 3
18
A-threads active: 0, B-threads active: 0
19
A-threads active: 0, B-threads active: 0
20
A-threads active: 0, B-threads active: 0
21