我只想在windows上看到一个简单的多处理代码实现,但它既没有在jupyternotebook中输入/运行函数,也没有运行保存的.py
import time
import multiprocessing
s=[1,4]
def subu(remo):
s[remo-1]=remo*9
print(f'here{remo}')
return
if __name__=="__main__":
p1=multiprocessing.Process(target=subu , args=[1])
p2=multiprocessing.Process(target=subu , args=[2])
p1.start()
p2.start()
p1.join()
p2.join()
# print("2222here")
print(s)
input()
.py的输出为:
[1, 4]
[1, 4]
jupyternotebook的输出为:
[1,4]
我希望成为:
here1
here2
[9,18]
上面的代码出了什么问题?这个代码呢:
import concurrent
thread_num=2
s=[1,4]
def subu(remo):
s[remo-1]=remo*9
print(f'here{remo}')
return
with concurrent.futures.ProcessPoolExecutor() as executor:
## or if __name__=="__main__":
##... with concurrent.futures.ProcessPoolExecutor() as executor:
results=[executor.submit(subu,i) for i in range(thread_num)]
for f in concurrent.futures.as_completed(results):
print(f.result())
input()
在jupyter拉取错误中根本不运行
BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.
我知道我不能指望jupyter运行多处理。但是saved.py也无法运行它。并且它在不等待input((的情况下退出
存在几个潜在问题。辅助函数需要是可导入的(至少在Windows上(,以便子进程可以找到它。由于子进程内存对父进程不可见,因此需要返回结果。因此,将工人放在一个单独的模块中
子模块.py
def subu(remo):
remo = remo*9
print(f'here{remo}')
return remo
并使用流程池的现有基础结构将辅助返回值返回给父级。你可以
import time
import multiprocessing
if __name__=="__main__":
with multiprocessing.Pool(2) as pool:
s = list(pool.map(subu, (1,2))) #here
print(s)
input()