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

标签 python multithreading

我是 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/

相关文章:

python - Tango 与 Django 第 6 章 - URL 不起作用

python - 将pyspark数据帧转换为python字典列表

python - Django : Type error at/<User: user1> is not JSON serializable

java - Thread.exit()行:not available error in integrating javafx into swing using jfxpanel

c - 报告计算进度的 C 方法是什么?

JAVA消费者-生产者多线程应用程序——代码流程

python - 从 peer 包中导入 conftest.py

python - shap_values 和explainer.expected_value 的输出是什么?

java - 等待并锁定相同资源的 Tomcat 线程

c++ - 如何阻止和唤醒 boost 线程?