如何并行运行具有多个进程(例如 2)的数组? 例如我有这样的代码:
from multiprocessing import Process, Value
import time, os
n=Value('i', 0)
l=[1, 2, 3, 4, 5]
def fun():
try:
while True:
#time.sleep(0.01) not used, explanation below
print os.getpid(), l[n.value]
n.value+=1
except:
return
for i in range(2):
p=Process(target=fun)
p.start()
预期输出应该是这样的:
111 1
112 2
111 3
112 4
111 5
但我得到:
111 1
111 2
111 3
111 4
111 5
只有一个进程正在通过数组运行。
我只能通过将 time.sleep()
设置为任何非常小的值来获得预期结果,但如果可能的话,我正在寻找没有它的解决方案。
最佳答案
问题是因为您的任务执行得非常快,执行的第一个进程甚至在第二个进程开始之前就完成了。这就是为什么调用 sleep()
可以“修复”问题,因为它会减慢任务速度,以便给第二次足够的时间来启动,因此它们可以同时运行一段时间
如果您将 l
列表放大很多,例如 l = range(1, 1001)
,您就可以在代码中看到这一点。
为了进一步说明这一点,下面是代码的修改版本,它还显示它们最终将同时运行。它还打印出有关每个任务中发生的情况的更多信息:
from multiprocessing import Process, Value
import time, os
n = Value('i', 0)
l = [1, 2, 3, 4, 5]
def fun(cycles):
assert cycles >= 0
while cycles:
try:
while True:
with n.get_lock():
print os.getpid(), l[n.value]
n.value += 1
except IndexError:
print('list index out of range exception occurred, resetting "n"')
with n.get_lock(): # Reset for another cycle
n.value = 0
except Exception as exc:
print('unexpected exception {} occurred'.format(exc))
break
cycles -= 1
print('{} task terminating'.format(os.getpid()))
if __name__ == '__main__':
cycles = 100
for i in range(2):
p = Process(target=fun, args=(cycles,))
p.start()
print('done')
关于python - 多处理:通过多个进程运行数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47026050/