Python中的多处理:无法取回我的结果(get())(很少发生)

时间:2012-11-05 13:28:00

标签: python multiprocessing

我在Python中使用Multiprocessing来向数据库(以及其他东西)发出多个请求:

po = multiprocessing.Pool()
for element in setOfElements:
    results.append(po.apply_async(myDBRequestModule, (element, other stuff...)))                    
po.close()
po.join()
for r in results:
    newSet.add(r.get())

myDBRequestModule返回我定义的对象,由一个列表和两个数字组成。我重新定义了哈希函数,以便在我的这些对象集合中定义我的意思:

class myObject:
    def __init__(self, aList, aNumber, anotherNumber):
        self.list = aList
        self.number1 = aNumber
        self.number2 = anotherNumber
    def __hash__(self):
        # turn elements of list into a string, in order to hash the string
        hash_text = ""
        for element in self.list:
            hash_text += str(element.x.id) # I use the ID of the element of my list...
        return hash(hash_text)
    def __eq__(self, other):
        self_hash_text = ""
        other_hash_text = ""
        for element in self.list:
            self_hash_text += str(element.x.id)
        for element in other.listDest:
            other_hash_text += str(element.x.id)
        return self_hash_text == other_hash_text 

在大多数情况下,它可以正常工作。两次,由于没有已知的原因,在完全相同的背景下,我有一个错误:

newSet.add(r.get())
File "/usr/lib/python2.6/multiprocessing/pool.py", line 422, in get
    raise self._value
TypeError: 'str' object does not support item assignment

它来自get方法(最后一行):

def get(self, timeout=None):
    self.wait(timeout)
    if not self._ready:
        raise TimeoutError
    if self._success:
        return self._value
    else:
        raise self._value

由于我只有一次这个错误并且它消失了,我决定早点放弃,但最近又产生了第二个问题,我真的不知道如何对付这个bug。 特别是,我很难说出为什么它几乎从未发生过,而且通常效果很好。

1 个答案:

答案 0 :(得分:1)

multiprocessing不是问题所在。

您尚未向我们提供正确的代码来诊断问题。在某些时候,您已为self._value分配了一个捕获的例外。这就是错误发生的地方。查看self._value被分配到的任何地方,您将找到发现此错误的途径。