gpt4 book ai didi

Python 多处理池 - 迭代对象方法?

转载 作者:太空狗 更新时间:2023-10-29 22:27:14 25 4
gpt4 key购买 nike

也许更精通 Python 的多处理池代码的人可以帮助我。我正在尝试通过套接字连接同时连接到我网络上的多个主机(任何时候都连接 N 个)并执行一些 RPC。当一个主机完成时,我想将下一个主机添加到池中运行,直到所有主机都完成。

我有一个类,HClass,有一些这样做的方法,以及主机列表中包含的主机名列表。但是我无法理解 Pool 的任何 docs.python.org 示例以使其正常工作。

一小段代码来说明我到目前为止所得到的:

hostlist = [h1, h2, h3, h4, ....]
poolsize = 2

class HClass:
def __init__(self, hostname="default"):
self.hostname = hostname

def go(self):
# do stuff
# do more stuff
....

if __name__ == "__main__":
objs = [HClass(hostname=current_host) for current_host in hostlist]
pool = multiprocessing.pool(poolsize)
results = pool.apply_async(objs.go())

到目前为止,我很幸运有这个回溯:

Exception in thread Thread-2:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 551, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 504, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.7/multiprocessing/pool.py", line 319, in _handle_tasks
put(task)
PicklingError: Can't pickle <type 'generator'>: attribute lookup __builtin__.generator failed

进程一直挂起,直到我按 Control-C 退出。

最佳答案

我会尽量减少进程间通信。看起来您真正需要发送的只是主机名字符串:

for host in hostlist:
pool.apply_async(worker, args = (host,), callback = on_return)

例如,

import multiprocessing as mp
import time
import logging

logger = mp.log_to_stderr(logging.INFO)

hostlist = ['h1', 'h2', 'h3', 'h4']*3
poolsize = 2

class HClass:
def __init__(self, hostname="default"):
self.hostname = hostname

def go(self):
logger.info('processing {h}'.format(h = self.hostname))
time.sleep(1)
return self.hostname

def worker(host):
h = HClass(hostname = host)
return h.go()

result = []
def on_return(retval):
result.append(retval)

if __name__ == "__main__":
pool = mp.Pool(poolsize)
for host in hostlist:
pool.apply_async(worker, args = (host,), callback = on_return)
pool.close()
pool.join()
logger.info(result)

关于Python 多处理池 - 迭代对象方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14116502/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com