在使用主持人脚本(参见下文(调用执行计算的内部脚本以线性方式很好地运行一些计算后,我挣扎着在尝试使用多处理时将其执行。 似乎每个 CPU 内核都在通过此列表集 (testRegister( 运行并启动计算,即使另一个内核之前已经执行了此任务(在同一会话中(。 如何防止这种混乱行为? 这是我第一次尝试通过Python调用多个处理器。
更正:最初的帖子没有显示测试是一个字符串,包括调用"内部脚本",其中包含不同的参数 m1 和 m2,以及仅属于此"内部脚本"的固定参数 arg1 和 arg2。
#!/usr/bin/env python3
import os
import subprocess as sub
import sys
import multiprocessing
fileRegister = []
testRegister = []
def fileCollector():
for file in os.listdir("."):
if file.endswith(".xyz"):
fileRegister.append(file)
fileRegister.sort()
return fileRegister
def testSetup():
data = fileRegister
while len(data) > 1:
for entry in fileRegister[1:]:
m0 = str(fileRegister[0])
m1 = str(entry)
test = str("python foo.py ") + str(m1) + str(" ") + str(m2) +
str(" --arg1 --arg2") # formulate test condition
testRegister.append(test)
testRegister.sort()
del data[0]
return testRegister
def shortAnalysator():
for entry in testRegister:
print(str(entry))
sub.call(entry, shell=True)
del testRegister[0]
def polyAnalysator():
# apparently each CPU core works as if the register were not shared
# reference: https://docs.python.org/3.7/library/multiprocessing.html
if __name__ == '__main__':
jobs = []
for i in range(3): # safety marging to not consume all CPU
p = multiprocessing.Process(target=shortAnalysator)
jobs.append(p)
p.start()
fileCollector()
testSetup()
shortAnalysator() # proceeding expectably on one CPU (slow)
# polyAnalysator() # causing irritation
sys.exit()```
您的polyAnalysator
运行了三次shortAnalysator
。尝试按如下方式更改polyAnalysator
,并添加f
方法。这将使用multiprocessing Pool
:
from multiprocessing import Pool
def f(test):
sub.call(test, shell=True)
def polyAnalysator():
# apparently each CPU core works as if the register were not shared
# reference: https://docs.python.org/3.7/library/multiprocessing.html
with Pool(3) as p:
p.map(f, testRegister)