我真的很沮丧。 为什么当队列对象作为参数或参数的一部分传递时,Python 的 multiprocessing.apply_async(( 实际上没有启动进程?
此代码按预期工作:
#! /usr/bin/env python3
import multiprocessing
import queue
import time
def worker(var):
while True:
print("Worker {}".format(var))
time.sleep(2)
pool = multiprocessing.Pool(20)
m = multiprocessing.Manager()
q = queue.Queue()
for i in range(20):
pool.apply_async(worker, (i,))
print("kicked off workers")
pool.close()
pool.join()
但是只需传递队列q
,现在运行它时什么都不会发生:
#! /usr/bin/env python3
import multiprocessing
import queue
import time
def worker(var,q):
while True:
print("Worker {}".format(var))
time.sleep(2)
pool = multiprocessing.Pool(20)
m = multiprocessing.Manager()
q = queue.Queue()
for i in range(20):
pool.apply_async(worker, (i,q))
print("kicked off workers")
pool.close()
pool.join()
再次;超级令人沮丧。 这到底是怎么回事? 我做错了什么?
当您想在进程之间共享Queue
时,您必须为具有multiprocessing.managers.SyncManager.Queue
的进程创建一个代理。
import multiprocessing
import time
def worker(var, q):
while True:
print("Worker {}".format(var))
time.sleep(2)
if __name__ == '__main__': # Be sure to include this.
pool = multiprocessing.Pool(20)
mgr = multiprocessing.Manager()
q = mgr.Queue() # Create a shared queue.Queue object.
for i in range(20):
pool.apply_async(worker, (i,q))
print("kicked off workers")
pool.close()
print('joining pool')
pool.join()
print('done')