加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何在不处于顶层的情况下解决python多处理的酸洗错误?

发布时间:2020-12-16 22:56:08 所属栏目:Python 来源:网络整理
导读:我已经多次研究过这个问题,但是没有找到一个可以在我的情况下工作的解决方法,或者我理解的解决方法,所以请耐心等待. 基本上,我有一个功能的层次组织,这阻止我在顶层进行多处理.不幸的是,我不相信我可以改变程序的布局 – 因为我需要在初始输入后创建的所有变
我已经多次研究过这个问题,但是没有找到一个可以在我的情况下工作的解决方法,或者我理解的解决方法,所以请耐心等待.

基本上,我有一个功能的层次组织,这阻止我在顶层进行多处理.不幸的是,我不相信我可以改变程序的布局 – 因为我需要在初始输入后创建的所有变量.

例如,说我有这个:

import multiprocessing

  def calculate(x):
    # here is where I would take this input x (and maybe a couple more inputs)
    # and build a larger library of variables that I use further down the line

    def domath(y):
      return x * y

    pool = multiprocessing.Pool(3)
    final= pool.map(domath,range(3))

calculate(2)

这会产生以下错误:

Can't pickle <type 'function'>: attribute lookup __builtin__.function failed

我在考虑全局,但我担心我必须定义太多,这可能会使我的程序减慢很多.
是否有任何解决方法而无需重组整个计划?

解决方法

您可以使用pathos.multiprocessing,它是使用dill序列化程序而不是pickle的多处理分支. dill可以在python中序列化几乎任何东西.然后,无需编辑您的代码.
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>> 
>>> def calculate(x):
...   def domath(y):
...     return x*y
...   return Pool().map(domath,range(3))
... 
>>> calculate(2)
[0,2,4]

你甚至可以坚持下去……因为大多数东西都是腌制的.不需要奇怪的非pythonic解决方案,您必须使用纯多处理进行烹饪.

>>> class Foo(object):
...   def __init__(self,x):
...     self.x = x
...   def doit(self,y):
...     return ProcessingPool().map(self.squared,calculate(y+self.x))
...   def squared(self,z):
...     return z*z
... 
>>> def thing(obj,y):
...   return getattr(obj,'doit')(y)
... 
>>> ProcessingPool().map(thing,ProcessingPool().map(Foo,range(3)),range(3))
[[0,0],[0,4,16],16,64]]

获取悲情:https://github.com/uqfoundation

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读