【问题标题】:python multiprocessing does not run functionspython多处理不运行函数
【发布时间】:2020-08-18 01:36:37
【问题描述】:

我只是想看看windows上多处理的简单代码实现,但它既不进入/运行函数,也不在jupyternotebook或运行保存的.py中p>

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 pull 错误中根本不运行

BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.

我知道我不能指望 jupyter 运行多处理。但 saved.py 也无法运行它。它不等待输入()就退出了

【问题讨论】:

  • 在 linux 的命令行上运行我得到了希望的结果。无法重现。
  • 好的,编辑那个,不太理想。 here1\nhere2\n[1,4]。 [9,18] 不会发生,因为父进程看不到子进程内存(写时复制或独立进程)。
  • @tdelaney 那么如何通过多处理对父级应用更改,以及'here1'和'here2'呢,为什么它们不会发生?
  • 我不是一个普通的 jupyter 用户,但只是四处寻找这个question 建议将工作人员放在一个单独的模块中,以便它可以由子进程导入。
  • 至于父级中的更改,您需要某种方式从进程与父级进行通信。 multiprocessing.queue() 可以是那个频道。而multiprocessing.Pool 也可以。由于我不知道jupyter部分,我不确定回答。

标签: python multiprocessing


【解决方案1】:

有几个潜在的问题。 worker 函数需要是可导入的(至少在 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()

【讨论】:

  • 我明白了如何用 s 列表处理你的意思,你的意思是我不能得到“here1”和“here2”,除非我把它们当作函数的输出?
  • 我很担心这个。令人失望。你在 Windows 上吗?在这种情况下,仅搜索“jupyter notebook 多处理窗口”是我唯一的建议。
  • 你需要将remu()的计算返回给父级。您可以创建一个multiprocessing.queue(),然后创建一个multiprocessing.Process(),然后将队列与呼叫一起传递。 Pool 为您完成这部分工作。 worker 函数的返回值在进程中被pickle,返回给父级,unpickled,然后从map 调用中迭代回来。 list 只是将返回值迭代变成一个列表。我在您的示例中注意到 s 中的初始值无关紧要。当然,这只是一个玩具示例,您可能需要做一些不同的事情。
  • 我没有得到队列部分,我是否需要.queue() 用于处理单独列表的示例。地图还不够吗?
  • 如果你使用地图,你就不会使用队列。
猜你喜欢
  • 2021-05-08
  • 2021-02-21
  • 2022-01-25
  • 1970-01-01
  • 2019-05-09
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 2020-09-19
相关资源
最近更新 更多