Skip to main content
 首页 » 编程设计

python 类型错误: can't pickle generator objects on using generators in combination with multiprocessing

2024年12月31日7softidea

我有一个函数 say fun() 可以生成 yield 生成器。我想检查生成器是否为空,因为我想尽可能多地节省运行时间,所以我 不要将其转换为列表并检查其是否为空。 相反,我这样做:

def peek(iterable): 
    try: 
        first = next(iterable) 
    except StopIteration: 
        return None 
    return first, itertools.chain([first], iterable) 

我像这样使用多处理:

def call_generator_obj(ret_val): 
    next = peek(ret_val) 
    if next is not None: 
        return False 
    else: 
        return True 
 
 
def main(): 
    import multiprocessing as mp 
    pool = mp.Pool(processes=mp.cpu_count()-1) 
    # for loop over here 
        ret_val = fun(args, kwargs) 
        results.append(pool.apply(call_generator_obj, args=(ret_val,)) 
        # the above line throws me the error 

据我所知,pickling 是将内存中的某个对象转换为字节流,而我在我的任何函数中都在做类似的事情。

TRACEBACK:(在尖线之后)

  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 253, in apply 
    return self.apply_async(func, args, kwds).get() 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 608, in get 
    raise self._value 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/pool.py", line 385, in _handle_tasks 
    put(task) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/connection.py", line 206, in send 
    self._send_bytes(_ForkingPickler.dumps(obj)) 
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/multiprocessing/reduction.py", line 51, in dumps 
    cls(buf, protocol).dump(obj) 
TypeError: can't pickle generator objects 

请您参考如下方法:

As far as I know pickling is when converting some object in memory to a byte stream and I don't think I am doing anything like that over here.

好吧,你正在这样做。

您不能在进程之间直接传递 Python 值。即使是最简单的变量也包含指向进程内存空间中某处结构的指针,只是将该指针复制到不同的进程会给你一个段错误或垃圾,这取决于另一个进程中的相同内存空间是未映射还是映射到完全不同的东西。像生成器这样复杂的东西——它基本上是一个实时堆栈框架——更不可能。

multiprocessing 解决这个问题的方法是透明地 pickle 传递给它的所有内容。函数及其参数和返回值都需要进行 pickle。

如果你想知道它在幕后是如何工作的:Pool 本质上是通过一个 Queue 来工作的,父级 put 的任务on——任务基本上是 (func, args) 对——而 children get 任务。 Queue 本质上是通过调用 pickle.dumps(value) 然后将结果写入管道或其他进程间通信机制来工作的。