python - 如何获取特定类启动的活动线程数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4046986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 14:00:11  来源:igfitidea点击:

python - how to get the number of active threads started by specific class?

pythonmultithreadingcount

提问by m1k3y3

code looks like below:

代码如下所示:

class workers1(Thread):
...   def __init__(self):
...      Thread.__init__(self)
...   def run(self):
...      ...do some stuff 

class workers2(Thread):
...   def __init__(self):
...      Thread.__init__(self)
...   def run(self):
...      ...do some stuff 


if __name__ == "__main__":
...   start workers 
while True: 
    print "Number of threads active", threading.activeCount()
    print "Number of worker1 threads", ?????, "Number of worker2 threads", ?????

Is there a way to get the number of threads being active by originating class ?

有没有办法通过原始类获取活动线程的数量?

采纳答案by unutbu

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:

这是对 Doug Hellman 的多处理 ActivePool 示例代码(使用线程)的一个小修改。这个想法是让你的工作人员在一个池中注册自己,当他们完成时取消注册自己,使用 threading.Lock 来协调池的活动列表的修改:

import threading
import time
import random

class ActivePool(object):
    def __init__(self):
        super(ActivePool, self).__init__()
        self.active=[]
        self.lock=threading.Lock()
    def makeActive(self, name):
        with self.lock:
            self.active.append(name)
    def makeInactive(self, name):
        with self.lock:
            self.active.remove(name)
    def numActive(self):
        with self.lock:
            return len(self.active)
    def __str__(self):
        with self.lock:
            return str(self.active)
def worker(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 in range(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

产量

Now running: ['A0']
Now running: ['B0']
Now running: ['A0', 'A1']
Now running: ['B0', 'B1']
 Now running: ['A0', 'A1', 'A2']
 Now running: ['B0', 'B1', 'B2']
Now running: ['A0', 'A1', 'A2', 'A3']
Now running: ['B0', 'B1', 'B2', 'B3']
Now running: ['A0', 'A1', 'A2', 'A3', 'A4']
Now running: ['B0', 'B1', 'B2', 'B3', 'B4']
A-threads active: 4, B-threads active: 5
A-threads active: 2, B-threads active: 5
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 0
A-threads active: 0, B-threads active: 0
A-threads active: 0, B-threads active: 0

回答by Scott

You can use a semaphore for each class and get their counts: see link.

您可以为每个类使用信号量并获取它们的计数:请参阅链接