如果我使用 Python 的 Threading 库,我可以更快地完成一批子进程吗?比方说,我需要将 100 个 .wav 文件转换为 .mp3 文件。如果我将“ffmpeg”包装在使用线程的 Python 脚本中,我可以更快地完成任务吗?线程是否使我能够实际使用我的 i7 中可用的所有 8 个线程?
我最近偶然发现了一个 Python 脚本,该脚本对主机列表执行 ping 操作,但利用线程来加快速度。脚本看起来很简洁,对于像我这样的初学者来说很容易阅读和理解。所以这就是我的另一个问题出现的地方:关于运行并行任务如此复杂的所有讨论是什么?可能我不懂parallel和parallel != threading。如果就这么简单,那么为什么人们在现代处理器上运行时不对任何和所有批处理转换使用线程?
最佳答案
这是针对您的案例的简单有效的解决方案。我经常使用它,事实证明它非常有用!此代码创建与核心一样多的线程,并让它们执行(大量)任务(在本例中,调用 shell 程序):
import Queue
import threading
import multiprocessing
import subprocess
q = Queue.Queue()
for i in range(30): #put 30 tasks in the queue
q.put(i)
def worker():
while True:
item = q.get()
#execute a task: call a shell program and wait until it completes
subprocess.call("echo "+str(item), shell=True)
q.task_done()
cpus=multiprocessing.cpu_count() #detect number of cores
print("Creating %d threads" % cpus)
for i in range(cpus):
t = threading.Thread(target=worker)
t.daemon = True
t.start()
q.join() #block until all tasks are done
关于python - Python 中的线程子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6906922/