python - 为大量线程类实现线程池

标签 python python-3.x multithreading threadpool

网上有很多关于线程池的示例,但几乎所有示例都涉及传递函数并调用它们的概念(例如 herehere )。但我有一些继承自 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/

相关文章:

python - Discord.py 机器人获取命令剩余冷却时间

java - 分析 Web 应用程序的线程转储

python - 在实践中,为什么比较整数比比较字符串更好?

linux - 如何在 Python 中找到闪存驱动器自动挂载的位置?

python - 使用itertools获得大量独特的排列

c# - RestSharp 异步后台线程

vb.net - VB.Net 中的线程安全

python - matplotlib,如何在给定条件下绘制 3d 2 变量函数

python: urllib2 如何使用 urlopen 请求发送 cookie

python - 训练期间的 Tensorflow Slim 调试