<p>如果您的子任务是真正并行的(不依赖于任何共享状态),那么您可以使用<code>multiprocesing.Pool()</code>实现这一点</p>
<p>看看
<a href="https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool" rel="nofollow noreferrer">https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool</a></p>
<p>这要求您使pool.map()的参数可序列化。您不能将生成器传递给工作程序,但可以通过在目标函数中定义生成器,并将初始化参数传递给多处理库来实现类似的功能:</p>
<pre><code>import multiprocessing as mp
import time
def worker(value):
# The generator is defined inside the multiprocessed function
def gen():
for k in range(value):
time.sleep(1) # Simulate long running task
yield k
# Execute the generator
for x in gen():
print(x)
# Do something with x?
pass
pool = mp.Pool()
pool.map(worker, [2, 5, 2])
pool.join() # Wait for all the work to be finished.
pool.close() # Clean up system resources
</code></pre>
<p>输出将是:</p>
<pre><code>0
0
0
1
1
1
2
3
4
</code></pre>
<p>请注意,此解决方案只有在您构建生成器,然后只使用它们一次时才真正起作用,因为它们的最终状态在辅助函数结束时丢失</p>
<p>请记住,由于进程间通信的限制,任何时候想要使用多处理时,都必须使用for serializable objects;这常常被证明是有限的</p>
<p>如果您的进程不受CPU限制,而是受I/O限制(磁盘访问、网络访问等),那么使用线程就会容易得多</p>