multiprocessing.Pool报pickling error

现象

multiprocessing.Pool传递一个普通方法(不在class中定义的)时, 能正常工作.

from multiprocessing import Pool

p = Pool(3)
def f(x):
return x*x p.map(f, [1,2,3])

但在class中定义的方法使用multiprocessing.Pool会报pickling error错误.

报错代码

# coding: utf8
import multiprocessing class MyTask(object):
def task(self, x):
return x*x def run(self):
pool = multiprocessing.Pool(processes=3) a = [1, 2, 3]
pool.map(self.task, a) if __name__ == '__main__':
t = MyTask()
t.run()

会出现如下异常:

cPickle.PicklingError: Can't pickle <type 'instancemethod'>: attribute lookup __builtin__.instancemethod failed

原因:
stackoverflow上的解释:
Pool methods all use a queue.Queue to pass tasks to the worker processes. Everything that goes through the queue.Queue must be pickable. So, multiprocessing can only transfer Python objects to worker processes which can be pickled. Functions are only picklable if they are defined at the top-level of a module, bound methods are not picklable.

pool方法都使用了queue.Queue将task传递给工作进程。multiprocessing必须将数据序列化以在进程间传递。方法只有在模块的顶层时才能被序列化,跟类绑定的方法不能被序列化,就会出现上面的异常。

解决方法:

  1. 用线程替换进程
  2. 可以使用copy_reg来规避上面的异常.
  3. dill 或pathos.multiprocesssing :use pathos.multiprocesssing, instead of multiprocessing. pathos.multiprocessing is a fork of multiprocessing that uses dill. dill can serialize almost anything in python, so you are able to send a lot more around in parallel.

正确代码1

 # coding: utf8
from multiprocessing.pool import ThreadPool as Pool class MyTask(object):
def task(self, x):
return x*x def run(self):
pool = Pool(3) a = [1, 2, 3]
ret = pool.map(self.task, a)
print ret if __name__ == '__main__':
t = MyTask()
t.run()

正确代码2:

# coding: utf8
import multiprocessing
import types
import copy_reg def _pickle_method(m):
if m.im_self is None:
return getattr, (m.im_class, m.im_func.func_name)
else:
return getattr, (m.im_self, m.im_func.func_name) copy_reg.pickle(types.MethodType, _pickle_method) class MyTask(object):
def __init__(self):
self.__result = [] def task(self, x):
return x * x def result_collector(self, result):
self.__result.append(result) def run(self):
pool = multiprocessing.Pool(processes=3) a = [1, 2, 3]
ret = pool.map(self.task, a)
print ret if __name__ == '__main__':
t = MyTask()
t.run()

python 2.7 类中使用多进程(multiprocessing)执行类函数时的问题

python 2.7 类中使用多进程(multiprocessing)执行类函数时报错

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

首先这是python2.7的一个bug,所以最简单的办法就是升级到python3

相关大神的文章的链接如下:

https://stackoverflow.com/questions/1816958/cant-pickle-type-instancemethod-when-using-multiprocessing-pool-map

http://bbs.chinaunix.net/thread-4111379-1-1.html

如果不升级python的话,就来改代码吧,我得改法如下:

import time
from multiprocessing import Pool
Class testClass():
def upMethod(self):
print '我是UP'
time.sleep(1)
def downMethod(self):
print '我是DOWN'
time.sleep(1)
def multiProcess(self):
p = Pool(2)
aObj=p.apply_async(self, args=('up',))#这里是重点
aObj=p.apply_async(self, args=('down',))#这里是重点
p.close()
p.join()
def __call__(self,sign):#这里是重点
if sign=='up':
return self.upMethod()
elif sign=='down':
return self.downMethod()
if __name__=='__main__':
testObj=testClass()
testObj.multiProcess()

关于__call__的说明 http://www.cnblogs.com/superxuezhazha/p/5793536.html

关于为什么这样改,大家看文章吧,我就不多BB了,有问题可以问我,大家一起探讨

multiprocessing.Pool报pickling error的更多相关文章

  1. python multiprocess pool模块报错pickling error

    问题 之前在调用class内的函数用multiprocessing模块的pool函数进行多线程处理的时候报了以下下错误信息: PicklingError: Can't pickle <type ...

  2. mysql报错"ERROR 1206 (HY000): The total number of locks exceeds the lock table size"的解决方法

    1. 问题背景         InnoDB是新版MySQL(v5.5及以后)默认的存储引擎,之前版本的默认引擎为MyISAM,因此,低于5.5版本的mysql配置文件.my.cnf中,关于InnoD ...

  3. 【MySQL笔记】mysql报错"ERROR 1206 (HY000): The total number of locks exceeds the lock table size"的解决方法

    step1:查看 1.1 Mysql命令行里输入"show engines:"查看innoddb数据引擎状态, 1.2 show variables "%_buffer% ...

  4. Appium - multiprocessing.pool.MaybeEncodingError-【 “Can’t pickle local object ‘PoolManager.__init__.<locals>.<lambda>‘】

    公司同事学习自动化新装环境后,run多进程测试用例时出错: multiprocessing.pool.MaybeEncodingError: Error sending result: ’<ap ...

  5. linux使用wkhtmltopdf报错error while loading shared libraries:

    官网提示 linux需要这些动态库.depends on: zlib, fontconfig, freetype, X11 libs (libX11, libXext, libXrender) 在li ...

  6. 发布报错:Error ITMS-90635 - Invalid Mach-O in bundle - submitting to App store

    发布报错:Error ITMS-90635 - Invalid Mach-O in bundle - submitting to App store 昨晚上传项目到AppStore,报了这个错,纳尼! ...

  7. python进程池:multiprocessing.pool

    本文转至http://www.cnblogs.com/kaituorensheng/p/4465768.html,在其基础上进行了一些小小改动. 在利用Python进行系统管理的时候,特别是同时操作多 ...

  8. javaMail使用163邮箱报535 Error: authentication failed

    javaMail使用网易163邮箱或者是126或者是网易其他邮箱报535 Error: authentication failed javax.mail.AuthenticationFailedExc ...

  9. 升级到macOS 10.12 mysqlb报错ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

    系统升级到macOS 10.12后启动mysql后,在终端输入mysql 报错ERROR 1045 (28000): Access denied for user 'root'@'localhost' ...

随机推荐

  1. DNS原理极限剖析

    how does DNS server work DNS Root Servers: The most critical infrastructure on the internet What is ...

  2. sqlserver 拼接字符串分割

    CREATE FUNCTION [dbo].[fnQuerySplit] ( @string VARCHAR(MAX) ,--待分割字符串 )--分割符 ) ) ) AS BEGIN DECLARE ...

  3. mxnet在windows使用gpu 出错

    1. cuda windows安装 官网下载 代码: import mxnet as mxfrom mxnet import ndfrom mxnet.gluon import nn a = nd.a ...

  4. 通过字节码分析this关键字以及异常表的重要作用

    在之前的字节码分析中缺少对异常的介绍,这次主要来对字节码异常表相关的东东进行一个学习,下面先来编写一个相关异常的小程序: 接着编译来看用javap -verbose来查看一下它的字节码信息: xion ...

  5. BCB 编写服务程序的一个注意事项

      BCB编写服务,install报错的一个问题 今天编写了一个服务,最后INSTALL 的时候报错,如图: 经过近1小时的比较(俺过去写例子),居然无意中设置了一个属性               ...

  6. Ubuntu 搭建 Ftp 服务器

    1.在 ubuntu 中 下载 vsftpd  要是你安装了 vsftpd  输入:vsftpd -v ,会有版本提示 如果没有,则进行安装 vsftpd 输入  apt-get install vs ...

  7. Air Raid POJ - 1422 【有向无环图(DAG)的最小路径覆盖【最小不相交路径覆盖】 模板题】

    Consider a town where all the streets are one-way and each street leads from one intersection to ano ...

  8. HTML的基础

    HTML:超文本标记语言                            超文本包括:文字.图片.音频.视频.动画等 流程:写好HTML代码后通过浏览器(自动编译HTML代码)展现出效果 HTM ...

  9. CodeForces - 999C Alphabetic Removals

    C - Alphabetic Removals ≤k≤n≤4⋅105) - the length of the string and the number of letters Polycarp wi ...

  10. Spring Cloud Eureka(六):Eureka Client 如何注册到Eureka Server

    1.本节概要 根据前文我们对Eureka Server 有了一定的了解,本节我们主要学习Eureka Client 与 Eureka Server 如何通讯的及相关通信机制是什么,本文会弄清楚一下几个 ...