异常问题:

在使用 concurrent.futures.ProcessPoolExecutor 出现一下异常:

TypeError: cannot pickle '_thread.lock' object

伪代码如下:

import concurrent.futures


class test:

    def __init__(self):
        """初始化一些东西"""

    def foo1(self, x):
        """一些代码"""
        return self.foo2(x)

    def foo2(self, x):
        """一些代码"""
        return x + x

    def run(self):
        data = [1, 2, 3, 4, 5, 6]
        with concurrent.futures.ProcessPoolExecutor(max_workers=5) as executor:
            for v, result in zip(data, executor.map(self.foo1, data)):
                print(f"{v} result: {result}")

问题原因

因为multiprocess进程池内部中使用了pickle模块进行序列化,但是传的参数是类下面定义的方法,所以无法序列化

解决办法

伪代码如下