我正在练习使用共享值进行多处理。我有一个使用共享值工作的现有 Process 函数:
def run_procs_with_loop(lock):
# this is my shared value
shared_number = Value('i', 0)
print(__name__, 'shared_value in the beginning', shared_number.value)
# create a process list to append each process spawned by the for- loop
processes = []
for _ in range(2):
p = Process(target=add_100_locking, args=(shared_number, lock))
processes.append(p)
p.start()
for _ in processes:
p.join()
print('shared_value at the end', shared_number.value)
上面的进程是针对spawn两个进程,每个进程都指向一个带有args(shared_number, lock)的函数。该函数按预期运行。
我试图将其转换为多处理池 - 我试图在我的 pool.map() 语句中传递参数 `[ shared_number, lock] *2 (我希望池只产生两个进程)但 python 拒绝它:
def run_procs_with_pool(lock):
shared_number = Value('i', 0)
print(__name__, 'shared_value in the beginning', shared_number.value)
# create processes using multiprocessing.Pool
pool = Pool()
pool.map(add_100_with_lock, [(shared_number,lock)] * 2)
print('shared_value at the end', shared_number.value)
感谢您提前提供任何有用的输入。
更新:
有人建议我使用星图而不是地图,但我得到了错误RuntimeError: Synchronized objects should only be shared between processes through inheritance
。看起来multiprocessing.Pool
不允许以这种方式传递共享值?
以为我会共享任务功能add_100_with_lock
,如下所示:
def add_100_with_lock(num,locking):
for _ in range(100):
time.sleep(0.001)
with lock:
num.value += 1
有没有办法让传递共享值与 multiprocessing.Pool 一起工作?