为大量线程实现线程池 类

Implementing thread pool for large number of thread classes

网上有很多关于线程池的示例,但几乎所有示例都涉及传递函数和调用这些函数的概念(如 or here)。但是我有一些继承自 threading.Thread 的对象,我只希望其中的一些对象在任何时候都是 运行ning。这是一个最小的工作示例

class Human (threading.Thread):
    def run (self):
        print ("taking a nap")
        sleep (60*60*8)

human_population = 7000000000

for i in range(human_population):
    human=Human()
    human.start()

暂时忽略 7B 对象会破坏我的计算机,我正在寻找一种非常简单的方法来 运行 任何时候只有可管理数量的线程,例如,N= 10 线程以先进先出的方式。

Semaphore 是非常适合这些情况的工具。您可以使用初始大小为 10 的信号量来控制一次最多可以激活多少个线程。

你的粗略实现(可能不应该为信号量使用全局变量,并且更干净地处理生命周期):

from threading import Thread, Semaphore
from time import sleep

SEM = Semaphore(10)
 
class Human(Thread):
    def run(self):
        print("taking a nap")
        sleep(5)
        SEM.release() # increments semaphore counter, notifying the job's done

human_population = 20

for i in range(human_population):
    SEM.acquire() # this will block when semaphore has value 0, and will wait until one of the active one finishes and calls release()
    human = Human()
    human.start()