multiprocessing.Pool报pickling error
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必须将数据序列化以在进程间传递。方法只有在模块的顶层时才能被序列化,跟类绑定的方法不能被序列化,就会出现上面的异常。
解决方法:
- 用线程替换进程
- 可以使用copy_reg来规避上面的异常.
- 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的更多相关文章
- python multiprocess pool模块报错pickling error
问题 之前在调用class内的函数用multiprocessing模块的pool函数进行多线程处理的时候报了以下下错误信息: PicklingError: Can't pickle <type ...
- 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 ...
- 【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% ...
- Appium - multiprocessing.pool.MaybeEncodingError-【 “Can’t pickle local object ‘PoolManager.__init__.<locals>.<lambda>‘】
公司同事学习自动化新装环境后,run多进程测试用例时出错: multiprocessing.pool.MaybeEncodingError: Error sending result: ’<ap ...
- linux使用wkhtmltopdf报错error while loading shared libraries:
官网提示 linux需要这些动态库.depends on: zlib, fontconfig, freetype, X11 libs (libX11, libXext, libXrender) 在li ...
- 发布报错: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,报了这个错,纳尼! ...
- python进程池:multiprocessing.pool
本文转至http://www.cnblogs.com/kaituorensheng/p/4465768.html,在其基础上进行了一些小小改动. 在利用Python进行系统管理的时候,特别是同时操作多 ...
- javaMail使用163邮箱报535 Error: authentication failed
javaMail使用网易163邮箱或者是126或者是网易其他邮箱报535 Error: authentication failed javax.mail.AuthenticationFailedExc ...
- 升级到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' ...
随机推荐
- IDAPython实战项目——DES算法识别
在CTF的逆向中我们需要的是找到加密的主函数,结合了yara的识别原理,通过对常量数组的引用的查找,一步步递归构建调用树.调用树根部就是可能的密码算法主函数. 由于这种办法需要常量分布于算法的各个步骤 ...
- window.onload 和doucument.ready执行顺序
浏览器渲染时 首先解析DOM结构 (同时在发送请求 去请求其他资源 比如图片 视频 等 ) DOM结构解析完毕 这个时候jQuery看准时机在这里添加了监听 所以Ready方法执行很早,可能会引起其他 ...
- python-----多线程笔记
多进程笔记: 多线程介绍: 多线程是为了同步完成多项任务,通过提高资源使用效率来提高系统的效率.线程是在同一时间需要完成多项任务的时候实现的. 最简单的比喻多线程就像火车的每一节车厢,而进程则是火车. ...
- mongoDB的基本操作之数据更新多条数据
在默认情况下,update会更新第一条找到的数据,我们做个实验,插入3条c为1的数据 db.test_collection.insert({c:1}) 然后我们find的一下 db.test_coll ...
- 导弹拦截( 二分+dilworth定理)
https://www.luogu.org/problemnew/show/P1020 原题 接下来是dilworth定理 https://blog.csdn.net/u011676717/artic ...
- How Many Answers Are Wrong(带权并查集)
题目 带权并查集的博客~ 题目: 多组输入数据.n,m.你不知道[1,n]内任意区间内值的和. m次询问,a b 是端点,都在n的范围以内 : v表示 [a,b]的区间内值的和.对每次询问,判断v是否 ...
- Django REST framework+Vue 打造生鲜电商项目(笔记一)
首先,这系列随笔是我个人在学习Bobby老师的Django实战项目中,记录的觉得对自己来说比较重要的知识点,不是完完整整的项目步骤过程....如果有小伙伴想找完整的教程,可以看看这个(https:// ...
- MySQL分组排序(取第一或最后)
MySQL分组排序(取第一或最后) 方法一:速度非常慢,跑了30分钟 SELECT custid, apply_date, rejectrule FROM ( SELECT *, IF ( , ) A ...
- 双向绑定v-bind
通过v-model绑定输出数据 <script> export default { data() { return { pagestyle:'https://v4.bootcss.com/ ...
- 关于pageHelper无法查到总数踩到的坑
问题代码 PageHelper.startPage(pageNum,pageSize); List<pojoVo> pojoVo=robotService.getPageList(); P ...