问题描述
我只想在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运行多处理。但save.py也无法运行。它退出而无需等待input()
解决方法
有两个潜在的问题。 worker函数需要是可导入的(至少在Windows上是这样),以便子进程可以找到它。而且由于子进程内存对于父级不可见,因此需要返回结果。因此,将工作人员放在单独的模块中
subumodule.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()