Python 在线程列表中一次处理有限的线程

Python 在线程列表中一次处理有限的线程,python,multithreading,queue,Python,Multithreading,Queue,我有一个python代码中的线程列表,非常大 threadlist = [thread1, thread2, thread3..........threadn] 当n大于200,我需要使用python队列一次处理10个线程时,我该怎么做。我们非常感谢你的建议 这似乎是一个使用该课程的好地方。它被明确设计为一次只允许有限数量的线程访问资源。您在主线程中创建一个信号量(10),然后让每个子线程在开始执行时调用acquire(),在结束时调用release。那么一次只运行10个

我有一个python代码中的线程列表,非常大

           threadlist = [thread1, thread2, thread3..........threadn]

当n大于200,我需要使用python队列一次处理10个线程时,我该怎么做。我们非常感谢你的建议

这似乎是一个使用该课程的好地方。它被明确设计为一次只允许有限数量的线程访问资源。您在主线程中创建一个信号量(10),然后让每个子线程在开始执行时调用
acquire()
,在结束时调用
release
。那么一次只运行10个

下面是一个将信号量处理抽象为线程子类的示例;但是,如果您不介意少一些封装的话,您也可以在目标函数中自己轻松地完成

from threading import Thread, Semaphore
import time

class PatientThread(Thread):
    MAXIMUM_SIMULTANEOUS_THREADS = 10
    _semaphore = Semaphore(MAXIMUM_SIMULTANEOUS_THREADS)
    def run(self):
        PatientThread._semaphore.acquire()
        super().run()
        PatientThread._semaphore.release()

def exampleTargetFunc(x):
    print(f"Thread #{x} is starting.")
    time.sleep(1)
    print(f"Thread #{x} is completing.")

threads = []
for i in range(200):
    threads.append(PatientThread(target=exampleTargetFunc, args=(i,)))
for t in threads:
    t.start()
for t in threads:
    t.join()
结果:

Thread #0 is starting.
Thread #1 is starting.
Thread #2 is starting.
Thread #3 is starting.
Thread #4 is starting.
Thread #5 is starting.
Thread #6 is starting.
Thread #7 is starting.
Thread #8 is starting.
Thread #9 is starting.
<a one second pause occurs here...>
Thread #2 is completing.
Thread #0 is completing.
Thread #1 is completing.
Thread #10 is starting.
Thread #11 is starting.
Thread #12 is starting.
Thread #4 is completing.
Thread #5 is completing.
Thread #3 is completing.
Thread #7 is completing.
Thread #13 is starting.
Thread #6 is completing.
Thread #16 is starting.
Thread #14 is starting.
Thread #15 is starting.
Thread #17 is starting.
Thread #9 is completing.
Thread #8 is completing.
Thread #18 is starting.
Thread #19 is starting.
<... And so on for the next 20 seconds>
线程0正在启动。
线程#1正在启动。
线程2正在启动。
线程#3正在启动。
线程4正在启动。
线程#5正在启动。
线程#6正在启动。
线程7正在启动。
线程8正在启动。
线程9正在启动。
线程2正在完成。
线程0正在完成。
线程#1正在完成。
线程#10正在启动。
线程11正在启动。
线程#12正在启动。
线程4正在完成。
线程#5正在完成。
线程#3正在完成。
线程#7正在完成。
线程#13正在启动。
线程#6正在完成。
线程#16正在启动。
线程#14正在启动。
线程#15正在启动。
线程#17正在启动。
线程9正在完成。
线程#8正在完成。
线程18正在启动。
线程19正在启动。
这表明线程10、11和12直到0、1和2完成才开始。螺纹3-9和螺纹13-19也是如此