我在一个类中有一个方法,需要在循环中完成大量工作,我想将工作分散到我的所有核心上。
我写了下面的代码,如果我使用正常的话,它可以工作map()
,但与pool.map()
返回错误。
import multiprocessing
pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)
class OtherClass:
def run(sentence, graph):
return False
class SomeClass:
def __init__(self):
self.sentences = [["Some string"]]
self.graphs = ["string"]
def some_method(self):
other = OtherClass()
def single(params):
sentences, graph = params
return [other.run(sentence, graph) for sentence in sentences]
return list(pool.map(single, zip(self.sentences, self.graphs)))
SomeClass().some_method()
Error 1:
AttributeError:无法腌制本地对象“SomeClass.some_method..single”
为什么不能腌制single()
?我什至尝试移动single()
到全局模块范围(不在类内部 - 使其独立于上下文):
import multiprocessing
pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)
class OtherClass:
def run(sentence, graph):
return False
def single(params):
other = OtherClass()
sentences, graph = params
return [other.run(sentence, graph) for sentence in sentences]
class SomeClass:
def __init__(self):
self.sentences = [["Some string"]]
self.graphs = ["string"]
def some_method(self):
return list(pool.map(single, zip(self.sentences, self.graphs)))
SomeClass().some_method()
我得到以下结果...
Error 2:
AttributeError:无法在模块'上获取属性'single'main' 来自 '.../test.py'