gpt4 book ai didi

python - 如何限制 python 中的事件线程数?

转载 作者:太空狗 更新时间:2023-10-29 18:13:38 27 4
gpt4 key购买 nike

我是 python 的新手,在 threading 方面取得了一些进展 - 我正在做一些音乐文件转换,希望能够利用我机器上的多个内核(每个内核一个事件转换线程)。

class EncodeThread(threading.Thread):
# this is hacked together a bit, but should give you an idea
def run(self):
decode = subprocess.Popen(["flac","--decode","--stdout",self.src],
stdout=subprocess.PIPE)
encode = subprocess.Popen(["lame","--quiet","-",self.dest],
stdin=decode.stdout)
encode.communicate()

# some other code puts these threads with various src/dest pairs in a list

for proc in threads: # `threads` is my list of `threading.Thread` objects
proc.start()

一切正常,所有文件都已编码,太棒了! ...但是,所有进程都会立即产生,但我只想一次运行两个(每个核心一个)。一旦一个完成,我希望它移动到列表中的下一个,直到它完成,然后继续该程序。

我该怎么做?

(我看过线程池和队列函数,但找不到简单的答案。)

编辑:也许我应该补充一点,我的每个线程都使用subprocess.Popen 来运行单独的命令行解码器 (flac)通过管道传输到标准输出,标准输出被输入命令行 编码器 (lame/mp3)。

最佳答案

如果你想限制并行线程的数量,使用semaphore :

threadLimiter = threading.BoundedSemaphore(maximumNumberOfThreads)

class EncodeThread(threading.Thread):

def run(self):
threadLimiter.acquire()
try:
<your code here>
finally:
threadLimiter.release()

同时启动所有线程。除了 maximumNumberOfThreads 之外的所有线程都将在 threadLimiter.acquire() 中等待,等待线程只会在另一个线程通过 threadLimiter.release() 时继续。

关于python - 如何限制 python 中的事件线程数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1787397/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com