Python 使用多处理管理器共享对象(类实例)

Python 使用多处理管理器共享对象(类实例),python,multiprocessing,multiprocessing-manager,Python,Multiprocessing,Multiprocessing Manager,我需要在python中的几个进程之间共享一个对象及其方法。我试图使用管理器(在模块多处理中),但它崩溃了。下面是生产者消费者的一个愚蠢示例,其中两个进程之间的共享对象只是一个包含四种方法的数字列表 from multiprocessing import Process, Condition, Lock from multiprocessing.managers import BaseManager import time, os lock = Lock() waitC =

我需要在python中的几个进程之间共享一个对象及其方法。我试图使用
管理器
(在模块
多处理
中),但它崩溃了。下面是生产者消费者的一个愚蠢示例,其中两个进程之间的共享对象只是一个包含四种方法的数字列表

from multiprocessing import Process, Condition, Lock  
from multiprocessing.managers import BaseManager  
import time, os  
  
lock = Lock()  
waitC = Condition(lock)  
waitP = Condition(lock)  
  
class numeri(object):  
    def __init__(self):  
        self.nl = []  
      
    def getLen(self):  
        return len(self.nl)  
      
    def stampa(self):  
        print self.nl  
          
    def appendi(self, x):  
        self.nl.append(x)  
      
    def svuota(self):  
        for i in range(len(self.nl)):  
            del self.nl[0]  
      
class numManager(BaseManager):  
    pass  
  
numManager.register('numeri', numeri, exposed = ['getLen', 'appendi', 'svuota', 'stampa'])  
  
def consume(waitC, waitP, listaNumeri):  
    lock.acquire()  
    if (listaNumeri.getLen() == 0):  
        waitC.wait()  
    listaNumeri.stampa()  
    listaNumeri.svuota()  
    waitP.notify()  
    lock.release()  
      
def produce(waitC, waitP, listaNumeri):  
    lock.acquire()  
    if (listaNumeri.getLen() > 0):  
        waitP.wait()  
    for i in range(10):  
        listaNumeri.appendi(i)  
    waitC.notify()  
    lock.release()  
  
      
def main():  
    mymanager = numManager()  
    mymanager.start()  
    listaNumeri = mymanager.numeri()  
    producer = Process(target = produce, args =(waitC, waitP, listaNumeri,))  
    producer.start()  
    time.sleep(2)  
    consumer = Process(target = consume, args =(waitC, waitP, listaNumeri,))  
    consumer.start()  
  
main() 
不管怎样,它总是这样崩溃,告诉我:

过程-3:
回溯(最近一次呼叫最后一次):
文件“/usr/lib/python2.7/multiprocessing/process.py”,第258行,在_bootstrap中
self.run()
文件“/usr/lib/python2.7/multiprocessing/process.py”,第114行,正在运行
自我目标(*自我参数,**自我参数)
文件“/trySemProc.py”,第61行,第2行
如果(listaNumeri.getLen()==0):
文件“”,第2行,在getLen中
文件“/usr/lib/python2.7/multiprocessing/managers.py”,第755行,在调用方法中
self._connect()
文件“/usr/lib/python2.7/multiprocessing/managers.py”,第742行,在_connect中
conn=self.\u客户端(self.\u token.address,authkey=self.\u authkey)
客户端中的文件“/usr/lib/python2.7/multiprocessing/connection.py”,第169行
c=SocketClient(地址)
SocketClient中的文件“/usr/lib/python2.7/multiprocessing/connection.py”,第293行
s、 连接(地址)
文件“/usr/lib/python2.7/socket.py”,第224行,meth格式
返回getattr(self.\u sock,name)(*args)
错误:[Errno 2]没有这样的文件或目录
那怎么了?我应该如何使用这些
管理器
来共享对象及其方法?

在子进程继续执行之前,必须确保您的进程不退出主进程。因此,将连接添加到代码中:

 consumer.join()
 producer.join()

在您调用了流程的
start()
方法之后。

那么您发现发生了什么了吗?我正试图在python3中做同样的事情