我正在尝试在rpyc
服务中使用多处理程序包,但是当我尝试从客户端调用公开函数时会得到ValueError: pickling is disabled
。我知道multiprocesing
包使用酸洗在进程之间传递信息,并且rpyc
不允许酸洗,因为它是不安全的协议(protocol)。因此,我不确定将多处理与rpyc一起使用的最佳方法(或者是否存在)。如何在rpyc服务中使用多重处理?这是服务器端代码:
import rpyc
from multiprocessing import Pool
class MyService(rpyc.Service):
def exposed_RemotePool(self, function, arglist):
pool = Pool(processes = 8)
result = pool.map(function, arglist)
pool.close()
return result
if __name__ == "__main__":
from rpyc.utils.server import ThreadedServer
t = ThreadedServer(MyService, port = 18861)
t.start()
这是产生错误的客户端代码:
import rpyc
def square(x):
return x*x
c = rpyc.connect("localhost", 18861)
result = c.root.exposed_RemotePool(square, [1,2,3,4])
print(result)
最佳答案
您可以在协议(protocol)配置中启用酸洗。配置存储为字典,您可以修改default并将其传递到服务器(protocol_config
=)和客户端(config =
)。您还需要定义要在客户端和服务器端并行化的功能。因此,这是server.py
的完整代码:
import rpyc
from multiprocessing import Pool
rpyc.core.protocol.DEFAULT_CONFIG['allow_pickle'] = True
def square(x):
return x*x
class MyService(rpyc.Service):
def exposed_RemotePool(self, function, arglist):
pool = Pool(processes = 8)
result = pool.map(function, arglist)
pool.close()
return result
if __name__ == "__main__":
from rpyc.utils.server import ThreadedServer
t = ThreadedServer(MyService, port = 18861, protocol_config = rpyc.core.protocol.DEFAULT_CONFIG)
t.start()
对于
client.py
,代码为:import rpyc
rpyc.core.protocol.DEFAULT_CONFIG['allow_pickle'] = True
def square(x):
return x*x
c = rpyc.connect("localhost", port = 18861, config = rpyc.core.protocol.DEFAULT_CONFIG)
result = c.root.exposed_RemotePool(square, [1,2,3,4])
print(result)