multiprocessing.Pool开发多进程程序时,在某个子进程执行函数使用了mysql-python连接数据库,
由于程序设计问题,没有捕获到所有异常,导致某个异常错误直接抛到Pool中,导致整个Pool挂了,其异常错误如下所示:
Exception in thread Thread-3:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 812, in __bootstrap_inner
self.run()
File "/usr/lib64/python2.7/threading.py", line 765, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib64/python2.7/multiprocessing/pool.py", line 376, in _handle_results
task = get()
File "/usr/lib/python2.7/site-packages/mysql/connector/errors.py", line 194, in __init__
'msg': self.msg.encode('utf8') if PY2 else self.msg
AttributeError: ("'int' object has no attribute 'encode'", <class 'mysql.connector.errors.Error'>,
(2055, "2055: Lost Connection to MySQL '192.169.36.189:3306', system error: timed out", None))
本文档基于以上问题对multiprocessing.Pool以及python-mysql-connector的源码实现进行分析,以定位具体的错误原因。解决方法其实很简单,不要让异常抛到Pool里就行。
问题产生场景
python 版本centos7.3自带的2.7.5版本,或者最新的python-2.7.14
mysql-connector库,版本是2.0及以上,可到官网下载最新版:mysql-connector