【问题标题】:Implementing thread pool for large number of thread classes为大量线程类实现线程池
【发布时间】:2021-01-31 04:35:49
【问题描述】:
网上有很多关于线程池的示例,但几乎所有示例都涉及传递函数和调用它们的概念(例如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 对象会破坏我的计算机的那一刻,我正在寻找一种非常简单的方法来在任何时候只运行可管理数量的线程,例如以 FIFO 方式运行N= 10 线程。
【问题讨论】:
标签:
python
python-3.x
multithreading
threadpool
【解决方案1】:
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()