网上有很多关于线程池的示例,但几乎所有示例都涉及传递函数并调用它们的概念(例如 here 或 here )。但我有一些继承自 threading.Thread 的对象,并且我只希望其中的一些对象随时运行。这是一个最小的工作示例
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()
关于python - 为大量线程类实现线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64392812/