在Python中对实例方法调用多处理池
我有一个驱动程序类,它有一个实例方法write。我正在尝试使用Python多处理将此实例方法应用于队列中的对象。 这是我的密码 类驱动程序:在Python中对实例方法调用多处理池,python,python-3.x,multiprocessing,Python,Python 3.x,Multiprocessing,我有一个驱动程序类,它有一个实例方法write。我正在尝试使用Python多处理将此实例方法应用于队列中的对象。 这是我的密码 类驱动程序: def __init__(self, arg1, arg2, arg3): #initialize def write(self, key): # do something 这是我在收藏中的称呼 def write_to_db(key, d=Driver(arg1=None, arg2=None, arg3=None)): d.w
def __init__(self, arg1, arg2, arg3):
#initialize
def write(self, key):
# do something
这是我在收藏中的称呼
def write_to_db(key, d=Driver(arg1=None, arg2=None, arg3=None)):
d.write(key)
def main():
.........
with multiprocessing.Pool(processes=8) as pool:
driver = Driver(arg1=arg1, arg2=arg2, arg3=arg3)
_ = pool.map(write_to_db, (arr, driver))
我得到以下错误:
TypeError: can't pickle _thread.RLock objects
我如何才能做到这一点?简单的答案是你不能,如果你有共享状态,那么对象将不可拾取,python将抛出一个错误。 答案很长,要做到这一点,您必须在池中的进程内实例化对象 可以用这种方式实例化池
with mp.Pool(processes=processes, initializer=_worker_init, initargs=(config,)) as pool:
results = pool.map(_worker_apply, resources)
config
如果要传递配置,则传递
resources
是此处的集合,各个进程将在其上工作
def _worker_init(config):
# initialize the object here
def _worker_apply(payload):
process = mp.current_process()
return process.simulator.apply(payload)# implement the apply function to manage state of the object
希望这能有所帮助。您能展示更多的代码吗?例如,我缺少了重要的
if\uuuu name\uuuu=“\uuuu main\uuuuu”
子句,如果我看对了,那么您的main()
-函数在类驱动程序
之外,对吗?在池中。map
,write\u to\u db
将只运行两次,一次以arr
作为参数,一次使用驱动程序
。这真的是你想要的吗?