【问题标题】:python no output when using pool.map_asyncpython 使用 pool.map_async 时没有输出
【发布时间】:2014-08-10 07:12:12
【问题描述】:

在处理由 pool.map 调用的函数中的数据时,我遇到了非常奇怪的问题。例如,以下代码按预期工作...

import csv
import multiprocessing
import itertools
from collections import deque

cur_best = 0
d_sol = deque(maxlen=9)
d_names = deque(maxlen=9)

**import CSV Data1**

def calculate(vals):
    #global cur_best
    sol = sum(int(x[2]) for x in vals)
    names = [x[0] for x in vals]
    print(", ".join(names) + " = " + str(sol))

def process():
    pool = multiprocessing.Pool(processes=4)
    prod = itertools.product(([x[2], x[4], x[10]] for x in Data1))
    result = pool.map_async(calculate, prod)
    pool.close()
    pool.join()
    return result

process()

现在,当我向 calculate() 添加一个简单的 if 语句时,我没有得到任何输出。

   def calculate(vals):
        #global cur_best
        sol = sum(int(x[2]) for x in vals)
        if sol > cur_best:
             cur_best = sol
             names = [x[0] for x in vals]
             print(", ".join(names) + " = " + str(cur_best))
             #would like to append cur_best and names to a deque

我已尝试调整声明“cur_best”的位置,但无济于事。

在进行计算时,我正在尝试跟踪“当前最佳”解决方案。在我的线性代码中,此逻辑位于嵌套的 for 循环中,我将每个新的 'cur_best' 附加到一个双端队列。

我的新问题是否与 pool.map 或 pool.map_async 的工作方式有关?我可以不再将我的 calculate() 函数视为一个线性循环吗?

我需要解决其他几个条件语句。我应该在代码的不同部分处理这个吗?如果是这样,具体是怎样的?

【问题讨论】:

  • global 在您的实际代码中被注释掉了吗?
  • 使用 multiprocessing 将创建多个进程(这里是 4 个),每个进程都有自己的全局 cur_best 值,因此您的代码结构将不起作用。
  • @JasonS 是的,全局被注释掉了
  • @ArminRigo 那么为什么每个进程不打印自己的结果呢?我不明白为什么我的输出为零

标签: python map multiprocessing pool itertools


【解决方案1】:

这里可能发生了两件事。首先,您没有看到从工作函数打印的任何内容的原因可能是因为它引发了异常。因为您使用的是map_async,所以在调用result.get() 之前,您实际上不会看到异常。但是,由于您在使用 map_async 后立即在池上调用 close/join,因此您可能应该只使用 map,这将阻塞直到所有工作完成(或引发异常) .我不确定为什么会发生异常(您提供的代码中没有任何内容),但我的猜测是您从列表中某处提取了错误的索引。

其次,正如 Armin Rigo 指出的那样,cur_best 并非在所有进程之间共享,因此您的逻辑不会按照您的预期方式工作。我认为最简单的选择是使用multiprocessing.Value 在共享内存中创建一个整数,所有进程都可以访问该整数。

要将获得的结果附加到deque,您需要使用multiprocessing.Manager 创建共享双端队列。 Manager 生成一个服务器进程,可以管理对对象的共享访问(如 deque)。您池中的每个进程(以及父进程)都可以访问Proxy 对象,该对象可以与管理器的进程通信以读取/写入共享对象。

这是一个展示上述所有内容的示例:

import itertools
import multiprocessing
from collections import deque
from multiprocessing.managers import BaseManager, MakeProxyType

class DequeManager(BaseManager):
   pass

BaseDequeProxy = MakeProxyType('BaseDequeProxy', (
    '__add__', '__contains__', '__delitem__', '__getitem__', '__len__',
    '__mul__', '__reversed__', '__rmul__', '__setitem__',
    'append', 'count', 'extend', 'extendleft', 'index', 'insert', 'pop', 
    'remove', 'reverse', 'sort', 'appendleft', 'popleft', 'rotate', 
    '__imul__'
    ))
class DequeProxy(BaseDequeProxy):
    def __iadd__(self, value):
        self._callmethod('extend', (value,))
        return self
    def __imul__(self, value):
        self._callmethod('__imul__', (value,))
        return self

DequeManager.register('deque', deque, DequeProxy)


cur_best = d_sol = d_names = None

def init_globals(best, sol, names):
    """ This will be called in each worker process. 

    A global variable (cur_best) will be created in each worker.
    Because it is a multiprocessing.Value, it will be shared
    between each worker, too.

    """
    global cur_best, d_sol, d_names
    cur_best = best
    d_sol = sol
    d_names = names

def calculate(vals):
    global cur_best
    sol = sum(int(x[2]) for x in vals)
    if sol > cur_best.value:
        cur_best.value = sol
        names = [x[0] for x in vals]
        print(", ".join(names) + " = " + str(cur_best.value))
        d_sol.append(cur_best.value)
        d_names.append(names)
    return sol

def process():
    global d_sol, d_names
    cur_best = multiprocessing.Value("I", 0)  # unsigned int

    m = DequeManager()
    m.start()
    d_sol = m.deque(maxlen=9)
    d_names = m.deque(maxlen=9)  

    pool = multiprocessing.Pool(processes=4, initializer=init_globals, 
                                initargs=(cur_best, d_sol, d_names))
    prod = itertools.product([x[2], x[4], x[10]] for x in Data1)
    result = pool.map(calculate, prod)  # map instead of map_async
    pool.close()
    pool.join()
    return result  # Result will be a list containing the value of `sol` returned from each worker call

if __name__ == "__main__":    
    print(process())

【讨论】:

  • ty 以获得如此详细的解释。一些问题:双端队列只返回一个值(即使设置为 maxlen=9)。最近的变化:在我的calculate()中我需要使用float所以它现在是sol = sum(float(x[2]) for x in vals) 同样在process()中我通过cur_best = multiprocessing从unsigned int更改为float .Value("f", 0)
  • 每个工作进程是否都在清除双端队列,然后附加最近的结果?查看 init_globals 的结构以及 cur_best = d_sol = d_names = None 是如何定义的......这是我最好的猜测
  • 做一些测试,我得到一个错误,说 AutoProxy[deque] 对象不支持索引。经过一些研究,我似乎需要从 BaseProxy 定义 iter 以使该类可迭代
  • @nodoze 只需使用d_sol.value 来获取实际的双端队列。
  • 对不起,我会在代码的什么地方使用它?打印 d_sol.value 不起作用。达到学习曲线...
猜你喜欢
  • 1970-01-01
  • 2012-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 2018-10-22
  • 1970-01-01
相关资源
最近更新 更多