tho*_*mad 10 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()
Run Code Online (Sandbox Code Playgroud)
一切正常,所有文件都被编码,勇敢!...但是,所有进程立即生成,但我只想一次运行两个(每个核心一个).一旦完成,我希望它继续到列表中的下一个,直到它完成,然后继续该程序.
我该怎么做呢?
(我查看了线程池和队列函数,但我找不到简单的答案.)
编辑:也许我应该添加我的每个线程subprocess.Popen用于运行单独的命令行解码器(flac)管道输出到stdout,它被送入命令行编码器(lame/mp3).
And*_*ner 34
如果要限制并行线程数,请使用信号量:
threadLimiter = threading.BoundedSemaphore(maximumNumberOfThreads)
class EncodeThread(threading.Thread):
def run(self):
threadLimiter.acquire()
try:
<your code here>
finally:
threadLimiter.release()
Run Code Online (Sandbox Code Playgroud)
立即启动所有线程.所有人maximumNumberOfThreads都会等待,threadLimiter.acquire()等待线程只会在另一个线程通过后才会继续threadLimiter.release().