多处理:运行 通过具有多个进程的数组?
multiprocessing: Run through an array with multiple processes?
如何运行通过具有多个进程(例如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()
"fixes" 的原因——这是因为它减慢了任务的速度,足以给第二次足够的时间来开始,所以它们可以同时 运行 一段时间
如果您将 l
列表扩大很多,例如 l = range(1, 1001)
。
,您可以在代码中看到这一点
为了进一步说明这一点,下面是您的代码的修改版本,它还显示最终它们都将同时 运行ning。它还会打印出更多关于每个任务中发生的事情的信息:
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')
如何运行通过具有多个进程(例如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()
"fixes" 的原因——这是因为它减慢了任务的速度,足以给第二次足够的时间来开始,所以它们可以同时 运行 一段时间
如果您将 l
列表扩大很多,例如 l = range(1, 1001)
。
为了进一步说明这一点,下面是您的代码的修改版本,它还显示最终它们都将同时 运行ning。它还会打印出更多关于每个任务中发生的事情的信息:
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')